From 50dbb6c3b03e7df6e21051b63458e61d0a2ba272 Mon Sep 17 00:00:00 2001 From: Taylor Steinberg Date: Mon, 16 Nov 2026 14:47:53 -0500 Subject: [PATCH] refactor: modernize syntax for Python 3.11 --- pyproject.toml | 6 +- rsconnect/actions.py | 77 +- rsconnect/actions_content.py | 55 +- rsconnect/actions_environment.py | 59 +- rsconnect/actions_integration.py | 33 +- rsconnect/api.py | 418 ++++---- rsconnect/bundle.py | 196 ++-- rsconnect/certificates.py | 2 +- rsconnect/connect_cloud.py | 50 +- rsconnect/device_login.py | 79 +- rsconnect/environment.py | 46 +- rsconnect/environment_node.py | 3 +- rsconnect/environment_r.py | 9 +- rsconnect/exception.py | 6 +- rsconnect/git_metadata.py | 11 +- rsconnect/http_support.py | 105 +- rsconnect/json_web_token.py | 10 +- rsconnect/log.py | 13 +- rsconnect/main.py | 955 +++++++++--------- rsconnect/metadata.py | 113 +-- rsconnect/models.py | 43 +- rsconnect/oauth.py | 93 +- rsconnect/preflight.py | 81 +- rsconnect/preflight_node.py | 113 ++- rsconnect/pyproject.py | 26 +- rsconnect/quickstart/quickstart.py | 20 +- rsconnect/snowflake.py | 8 +- rsconnect/subprocesses/inspect_environment.py | 39 +- rsconnect/timeouts.py | 5 +- rsconnect/validation.py | 66 +- rsconnect/version_check.py | 18 +- tests/_local_run.py | 12 +- tests/conftest.py | 2 +- tests/target_helpers.py | 18 +- tests/test_bundle.py | 1 - tests/test_conftest.py | 2 +- tests/test_connect_cloud.py | 18 +- tests/test_environment.py | 2 +- tests/test_http_support.py | 5 +- tests/test_json_web_token.py | 24 +- tests/test_main.py | 60 +- tests/test_main_content.py | 8 +- tests/test_main_environment.py | 20 +- tests/test_main_integration.py | 16 +- tests/test_main_system_caches.py | 4 +- tests/test_metadata.py | 8 +- tests/test_oauth.py | 2 +- tests/test_oauth_token.py | 3 +- tests/test_package_installer.py | 2 +- tests/test_preflight_integration.py | 10 +- tests/test_quickstart.py | 12 +- tests/test_snowflake.py | 7 +- tests/test_target_inference.py | 4 +- 53 files changed, 1484 insertions(+), 1514 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 37c9e1739..c2ba29171 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,11 +60,13 @@ module-root = "" [tool.ruff] line-length = 120 +target-version = "py311" extend-exclude = ["rsconnect-build", "rsconnect-build-test", "tests/testdata"] [tool.ruff.lint] -select = ["E", "F", "W"] -ignore = ["E203", "E231", "E302"] +select = ["E", "F", "W", "UP"] +# Percent formatting has subtly different behavior from str.format. +ignore = ["E203", "E231", "E302", "UP031"] per-file-ignores = { "tests/test_metadata.py" = ["E501"] } [tool.coverage.run] diff --git a/rsconnect/actions.py b/rsconnect/actions.py index efaa5bd0b..0772fed37 100644 --- a/rsconnect/actions.py +++ b/rsconnect/actions.py @@ -15,7 +15,8 @@ import typing from os.path import basename, exists, isdir, join, relpath from pathlib import PurePath -from typing import NotRequired, Optional, Sequence, TypedDict, cast +from typing import NotRequired, TypedDict, cast +from collections.abc import Sequence from urllib.parse import urlparse from warnings import warn @@ -187,7 +188,7 @@ def test_rstudio_server(server: api.PositServer): try: client.get_current_user() except RSConnectException as exc: - raise RSConnectException("Failed to verify with {} ({}).".format(server.remote_name, exc)) + raise RSConnectException(f"Failed to verify with {server.remote_name} ({exc}).") def test_spcs_server(server: api.SPCSConnectServer): @@ -195,7 +196,7 @@ def test_spcs_server(server: api.SPCSConnectServer): try: client.me() except RSConnectException as exc: - raise RSConnectException("Failed to verify with {} ({}).".format(server.remote_name, exc)) + raise RSConnectException(f"Failed to verify with {server.remote_name} ({exc}).") def test_api_key(connect_server: api.RSConnectServer) -> str: @@ -210,7 +211,7 @@ def test_api_key(connect_server: api.RSConnectServer) -> str: return api.verify_api_key(connect_server) -def which_quarto(quarto: Optional[str] = None) -> str: +def which_quarto(quarto: str | None = None) -> str: """ Identify a valid Quarto executable. When a Quarto location is not provided as input, an attempt is made to discover Quarto from the PATH and other @@ -342,7 +343,7 @@ def validate_extra_files(directory: str, extra_files: Sequence[str]): return result -def validate_entry_point(entry_point: Optional[str], directory: str): +def validate_entry_point(entry_point: str | None, directory: str): """ Validates the entry point specified by the user, expanding as necessary. If the user specifies nothing, a module of "app" is assumed. If the user specifies a @@ -364,31 +365,31 @@ def validate_entry_point(entry_point: Optional[str], directory: str): def deploy_app( - name: Optional[str] = None, - server: Optional[str] = None, - api_key: Optional[str] = None, - insecure: Optional[bool] = None, - cacert: Optional[typing.IO[str]] = None, - ca_data: Optional[str] = None, - entry_point: Optional[str] = None, - excludes: Optional[list[str]] = None, + name: str | None = None, + server: str | None = None, + api_key: str | None = None, + insecure: bool | None = None, + cacert: typing.IO[str] | None = None, + ca_data: str | None = None, + entry_point: str | None = None, + excludes: list[str] | None = None, new: bool = False, - app_id: Optional[str] = None, - title: Optional[str] = None, - python: Optional[str] = None, + app_id: str | None = None, + title: str | None = None, + python: str | None = None, force_generate: bool = False, - verbose: Optional[bool] = None, - directory: Optional[str] = None, - extra_files: Optional[list[str]] = None, - env_vars: Optional[dict[str, str]] = None, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - account: Optional[str] = None, - token: Optional[str] = None, - secret: Optional[str] = None, - app_mode: Optional[AppMode] = None, - connect_server: Optional[api.TargetableServer] = None, + verbose: bool | None = None, + directory: str | None = None, + extra_files: list[str] | None = None, + env_vars: dict[str, str] | None = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + account: str | None = None, + token: str | None = None, + secret: str | None = None, + app_mode: AppMode | None = None, + connect_server: api.TargetableServer | None = None, **kws: object, ): kwargs = locals() @@ -480,8 +481,8 @@ def deploy_app( def deploy_python_fastapi( connect_server: api.TargetableServer, directory: str, - extra_files: typing.List[str], - excludes: typing.List[str], + extra_files: list[str], + excludes: list[str], entry_point: str, new: bool, app_id: int, @@ -490,9 +491,9 @@ def deploy_python_fastapi( conda_mode: bool, force_generate: bool, log_callback: typing.Callable[..., None], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, ): """ A function to deploy a Python ASGI API module to Posit Connect. Depending on the files involved @@ -531,11 +532,11 @@ def create_quarto_deployment_bundle( excludes: Sequence[str], app_mode: AppMode, inspect: QuartoInspectResult, - environment: Optional[Environment], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + environment: Environment | None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> typing.IO[bytes]: """ Create an in-memory bundle, ready to deploy. diff --git a/rsconnect/actions_content.py b/rsconnect/actions_content.py index 4a188758f..9ba5fff98 100644 --- a/rsconnect/actions_content.py +++ b/rsconnect/actions_content.py @@ -9,7 +9,8 @@ import traceback from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime, timedelta -from typing import Iterator, Literal, Optional, Sequence, cast, Union +from typing import Literal, cast +from collections.abc import Iterator, Sequence import semver @@ -33,7 +34,7 @@ def content_build_store() -> ContentBuildStore: return _content_build_store -def ensure_content_build_store(connect_server: Union[RSConnectServer, SPCSConnectServer]) -> ContentBuildStore: +def ensure_content_build_store(connect_server: RSConnectServer | SPCSConnectServer) -> ContentBuildStore: global _content_build_store if not _content_build_store: logger.info("Initializing ContentBuildStore for %s" % connect_server.url) @@ -42,7 +43,7 @@ def ensure_content_build_store(connect_server: Union[RSConnectServer, SPCSConnec def build_add_content( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, content_guids_with_bundle: Sequence[ContentGuidWithBundle], ): """ @@ -77,7 +78,7 @@ def build_add_content( build_store.set_content_item_build_status(content["guid"], BuildStatus.NEEDS_BUILD) -def _validate_build_rm_args(guid: Optional[str], all: bool, purge: bool): +def _validate_build_rm_args(guid: str | None, all: bool, purge: bool): if guid and all: raise RSConnectException("You must specify only one of -g/--guid or --all, not both.") if not guid and not all: @@ -85,8 +86,8 @@ def _validate_build_rm_args(guid: Optional[str], all: bool, purge: bool): def build_remove_content( - connect_server: Union[RSConnectServer, SPCSConnectServer], - guid: Optional[str], + connect_server: RSConnectServer | SPCSConnectServer, + guid: str | None, all: bool, purge: bool, ) -> list[str]: @@ -109,7 +110,7 @@ def build_remove_content( return guids -def build_list_content(connect_server: Union[RSConnectServer, SPCSConnectServer], guid: str, status: Optional[str]): +def build_list_content(connect_server: RSConnectServer | SPCSConnectServer, guid: str, status: str | None): build_store = ensure_content_build_store(connect_server) if guid: return [build_store.get_content_item(g) for g in guid] @@ -117,12 +118,12 @@ def build_list_content(connect_server: Union[RSConnectServer, SPCSConnectServer] return build_store.get_content_items(status=status) -def build_history(connect_server: Union[RSConnectServer, SPCSConnectServer], guid: str): +def build_history(connect_server: RSConnectServer | SPCSConnectServer, guid: str): return ensure_content_build_store(connect_server).get_build_history(guid) def build_start( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, parallelism: int, aborted: bool = False, error: bool = False, @@ -251,9 +252,7 @@ def build_start( build_monitor.shutdown() -def _monitor_build( - connect_server: Union[RSConnectServer, SPCSConnectServer], content_items: list[ContentItemWithBuildState] -): +def _monitor_build(connect_server: RSConnectServer | SPCSConnectServer, content_items: list[ContentItemWithBuildState]): """ :return bool: True if the build completed without errors, False otherwise """ @@ -299,7 +298,7 @@ def _monitor_build( def _build_content_item( - connect_server: Union[RSConnectServer, SPCSConnectServer], content: ContentItemWithBuildState, poll_wait: int + connect_server: RSConnectServer | SPCSConnectServer, content: ContentItemWithBuildState, poll_wait: int ): build_store = ensure_content_build_store(connect_server) with RSConnectClient(connect_server) as client: @@ -353,15 +352,15 @@ def write_log(line: str): def emit_build_log( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, guid: str, format: str, - task_id: Optional[str] = None, + task_id: str | None = None, ): build_store = ensure_content_build_store(connect_server) log_file = build_store.get_build_log(guid, task_id) if log_file: - with open(log_file, "r") as f: + with open(log_file) as f: for line in f.readlines(): if format == "json": yield json.dumps({"message": line}) + "\n" @@ -371,7 +370,7 @@ def emit_build_log( raise RSConnectException("Log file not found for content: %s" % guid) -def download_bundle(connect_server: Union[RSConnectServer, SPCSConnectServer], guid_with_bundle: ContentGuidWithBundle): +def download_bundle(connect_server: RSConnectServer | SPCSConnectServer, guid_with_bundle: ContentGuidWithBundle): """ :param guid_with_bundle: models.ContentGuidWithBundle """ @@ -389,12 +388,12 @@ def download_bundle(connect_server: Union[RSConnectServer, SPCSConnectServer], g return client.download_bundle(guid_with_bundle.guid, guid_with_bundle.bundle_id) -def download_lockfile(connect_server: Union[RSConnectServer, SPCSConnectServer], guid: str): +def download_lockfile(connect_server: RSConnectServer | SPCSConnectServer, guid: str): with RSConnectClient(connect_server) as client: return client.content_lockfile(guid) -def get_content(connect_server: Union[RSConnectServer, SPCSConnectServer], guid: str | list[str]): +def get_content(connect_server: RSConnectServer | SPCSConnectServer, guid: str | list[str]): """ :param guid: a single guid as a string or list of guids. :return: a list of content items. @@ -408,14 +407,14 @@ def get_content(connect_server: Union[RSConnectServer, SPCSConnectServer], guid: def search_content( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, published: bool, unpublished: bool, content_type: Sequence[str], - r_version: Optional[VersionSearchFilter], - py_version: Optional[VersionSearchFilter], - title_contains: Optional[str], - order_by: Optional[Literal["created", "last_deployed"]], + r_version: VersionSearchFilter | None, + py_version: VersionSearchFilter | None, + title_contains: str | None, + order_by: Literal["created", "last_deployed"] | None, ): with RSConnectClient(connect_server) as client: result = client.search_content() @@ -430,9 +429,9 @@ def _apply_content_filters( published: bool, unpublished: bool, content_type: Sequence[str], - r_version: Optional[VersionSearchFilter], - py_version: Optional[VersionSearchFilter], - title_search: Optional[str], + r_version: VersionSearchFilter | None, + py_version: VersionSearchFilter | None, + title_search: str | None, ) -> Iterator[ContentItemV1]: def content_is_published(item: ContentItemV1): return item.get("bundle_id") is not None @@ -495,7 +494,7 @@ def do_filter(item: ContentItemV1) -> bool: def _order_content_results( content_list: Iterator[ContentItemV1], - order_by: Optional[Literal["created", "last_deployed"]], + order_by: Literal["created", "last_deployed"] | None, ) -> list[ContentItemV1]: result = content_list if order_by == "last_deployed": diff --git a/rsconnect/actions_environment.py b/rsconnect/actions_environment.py index 0c9b0c93a..a09d90b25 100644 --- a/rsconnect/actions_environment.py +++ b/rsconnect/actions_environment.py @@ -4,7 +4,6 @@ from __future__ import annotations -from typing import Optional, Union from .api import RSConnectClient, RSConnectServer, SPCSConnectServer from .models import ( @@ -20,14 +19,14 @@ def list_environments( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, ) -> list[EnvironmentV1]: with RSConnectClient(connect_server) as client: return client.environment_list() def get_environment( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, guid: str, ) -> EnvironmentV1: with RSConnectClient(connect_server) as client: @@ -35,19 +34,19 @@ def get_environment( def create_environment( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, image: str, - title: Optional[str] = None, - description: Optional[str] = None, - matching: Optional[str] = None, - supervisor: Optional[str] = None, - python: Optional[list[EnvironmentInstallation]] = None, - quarto: Optional[list[EnvironmentInstallation]] = None, - r: Optional[list[EnvironmentInstallation]] = None, - tensorflow: Optional[list[EnvironmentInstallation]] = None, - volume_mounts: Optional[list[EnvironmentVolumeMount]] = None, - user_guids: Optional[list[str]] = None, - group_guids: Optional[list[str]] = None, + title: str | None = None, + description: str | None = None, + matching: str | None = None, + supervisor: str | None = None, + python: list[EnvironmentInstallation] | None = None, + quarto: list[EnvironmentInstallation] | None = None, + r: list[EnvironmentInstallation] | None = None, + tensorflow: list[EnvironmentInstallation] | None = None, + volume_mounts: list[EnvironmentVolumeMount] | None = None, + user_guids: list[str] | None = None, + group_guids: list[str] | None = None, ) -> EnvironmentV1: body: EnvironmentCreateInput = { "cluster_name": "Kubernetes", @@ -80,19 +79,19 @@ def create_environment( def update_environment( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, guid: str, - title: Optional[str] = None, - description: Optional[str] = None, - matching: Optional[str] = None, - supervisor: Optional[str] = None, - python: Optional[list[EnvironmentInstallation]] = None, - quarto: Optional[list[EnvironmentInstallation]] = None, - r: Optional[list[EnvironmentInstallation]] = None, - tensorflow: Optional[list[EnvironmentInstallation]] = None, - volume_mounts: Optional[list[EnvironmentVolumeMount]] = None, - user_guids: Optional[list[str]] = None, - group_guids: Optional[list[str]] = None, + title: str | None = None, + description: str | None = None, + matching: str | None = None, + supervisor: str | None = None, + python: list[EnvironmentInstallation] | None = None, + quarto: list[EnvironmentInstallation] | None = None, + r: list[EnvironmentInstallation] | None = None, + tensorflow: list[EnvironmentInstallation] | None = None, + volume_mounts: list[EnvironmentVolumeMount] | None = None, + user_guids: list[str] | None = None, + group_guids: list[str] | None = None, ) -> EnvironmentV1: with RSConnectClient(connect_server) as client: existing = client.environment_get(guid) @@ -119,7 +118,7 @@ def update_environment( def delete_environment( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, guid: str, ) -> None: with RSConnectClient(connect_server) as client: @@ -133,8 +132,8 @@ def _make_installations(items: list[EnvironmentInstallation]) -> EnvironmentInst def _sync_permissions( client: RSConnectClient, env_guid: str, - user_guids: Optional[list[str]], - group_guids: Optional[list[str]], + user_guids: list[str] | None, + group_guids: list[str] | None, ) -> list[EnvironmentPermissionV1]: existing = client.environment_permission_list(env_guid) diff --git a/rsconnect/actions_integration.py b/rsconnect/actions_integration.py index 3fc299bdf..30accc09a 100644 --- a/rsconnect/actions_integration.py +++ b/rsconnect/actions_integration.py @@ -4,7 +4,6 @@ from __future__ import annotations -from typing import Optional, Union from .api import RSConnectClient, RSConnectServer, SPCSConnectServer from .models import ( @@ -17,14 +16,14 @@ def list_oauth_integrations( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, ) -> list[OAuthIntegration]: with RSConnectClient(connect_server) as client: return client.oauth_integration_list() def get_oauth_integration( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, guid: str, ) -> OAuthIntegration: with RSConnectClient(connect_server) as client: @@ -32,13 +31,13 @@ def get_oauth_integration( def create_oauth_integration( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, template: str, config: dict[str, object], - name: Optional[str] = None, - description: Optional[str] = None, - user_guids: Optional[list[str]] = None, - group_guids: Optional[list[str]] = None, + name: str | None = None, + description: str | None = None, + user_guids: list[str] | None = None, + group_guids: list[str] | None = None, ) -> OAuthIntegration: permissions: list[OAuthIntegrationPermission] = [] for g in user_guids or []: @@ -62,13 +61,13 @@ def create_oauth_integration( def update_oauth_integration( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, guid: str, - config: Optional[dict[str, object]] = None, - name: Optional[str] = None, - description: Optional[str] = None, - user_guids: Optional[list[str]] = None, - group_guids: Optional[list[str]] = None, + config: dict[str, object] | None = None, + name: str | None = None, + description: str | None = None, + user_guids: list[str] | None = None, + group_guids: list[str] | None = None, ) -> OAuthIntegration: with RSConnectClient(connect_server) as client: body: OAuthIntegrationUpdate = {} @@ -96,7 +95,7 @@ def update_oauth_integration( def delete_oauth_integration( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, guid: str, ) -> None: with RSConnectClient(connect_server) as client: @@ -104,14 +103,14 @@ def delete_oauth_integration( def list_oauth_templates( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, ) -> list[OAuthTemplate]: with RSConnectClient(connect_server) as client: return client.oauth_template_list() def get_oauth_template( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, key: str, ) -> OAuthTemplate: with RSConnectClient(connect_server) as client: diff --git a/rsconnect/api.py b/rsconnect/api.py index 04fa9506e..d2bf0ceaf 100644 --- a/rsconnect/api.py +++ b/rsconnect/api.py @@ -23,20 +23,16 @@ IO, TYPE_CHECKING, Any, - Callable, - List, Literal, - Mapping, NamedTuple, NotRequired, - Optional, ParamSpec, TypedDict, TypeVar, - Union, cast, overload, ) +from collections.abc import Callable, Mapping from urllib import parse from urllib.parse import urlencode, urlparse from warnings import warn @@ -240,14 +236,14 @@ class ConnectCloudServer(AbstractRemoteServer): def __init__( self, account_name: str, - access_token: Optional[str] = None, - refresh_token: Optional[str] = None, - client_id: Optional[str] = None, - client_secret: Optional[str] = None, - url: Optional[str] = None, - server_name: Optional[str] = None, - account_id: Optional[str] = None, - oauth_client_id: Optional[str] = None, + access_token: str | None = None, + refresh_token: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, + url: str | None = None, + server_name: str | None = None, + account_id: str | None = None, + oauth_client_id: str | None = None, ): # Accepts the bare "connect.posit.cloud" a user types for --server, the # same way ShinyappsServer accepts "shinyapps.io". @@ -287,13 +283,13 @@ class RSConnectServer(AbstractRemoteServer): def __init__( self, url: str, - api_key: Optional[str], + api_key: str | None, insecure: bool = False, - ca_data: Optional[str | bytes] = None, - bootstrap_jwt: Optional[str] = None, - oauth_access_token: Optional[str] = None, - oauth_client_id: Optional[str] = None, - server_name: Optional[str] = None, + ca_data: str | bytes | None = None, + bootstrap_jwt: str | None = None, + oauth_access_token: str | None = None, + oauth_client_id: str | None = None, + server_name: str | None = None, ): super().__init__(url, "Posit Connect") self.api_key = api_key @@ -320,10 +316,10 @@ class SPCSConnectServer(AbstractRemoteServer): def __init__( self, url: str, - api_key: Optional[str], - snowflake_connection_name: Optional[str], + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool = False, - ca_data: Optional[str | bytes] = None, + ca_data: str | bytes | None = None, ): super().__init__(url, "Posit Connect (SPCS)") self.snowflake_connection_name = snowflake_connection_name @@ -442,7 +438,7 @@ def exchange_token(self) -> str: raise RSConnectException(f"Failed to exchange Snowflake token: {str(e)}") from e -TargetableServer = typing.Union[ShinyappsServer, RSConnectServer, SPCSConnectServer, ConnectCloudServer] +TargetableServer = ShinyappsServer | RSConnectServer | SPCSConnectServer | ConnectCloudServer class S3Server(AbstractRemoteServer): @@ -461,7 +457,7 @@ class RSConnectClientDeployResult(TypedDict): title: str | None -def server_supports_git_metadata(server_version: Optional[str]) -> bool: +def server_supports_git_metadata(server_version: str | None) -> bool: """ Check if the server version supports git metadata in bundle uploads. @@ -491,7 +487,7 @@ def server_supports_git_metadata(server_version: Optional[str]) -> bool: } -def server_supports_draft_deploy(server_version: Optional[str]) -> bool: +def server_supports_draft_deploy(server_version: str | None) -> bool: """ Check if the server supports deploying a bundle as a draft and activating it separately, i.e. the ``activate`` field on the content deploy/build endpoints. @@ -515,7 +511,7 @@ def server_supports_draft_deploy(server_version: Optional[str]) -> bool: class RSConnectClient(BearerTokenHTTPServer): - def __init__(self, server: Union[RSConnectServer, SPCSConnectServer], cookies: Optional[CookieJar] = None): + def __init__(self, server: RSConnectServer | SPCSConnectServer, cookies: CookieJar | None = None): if cookies is None: cookies = server.cookie_jar super().__init__( @@ -585,16 +581,16 @@ def _tweak_response(self, response: HTTPResponse) -> JsonData | HTTPResponse: ) def me(self) -> UserRecord: - response = cast(Union[UserRecord, HTTPResponse], self.get("v1/user")) + response = cast(UserRecord | HTTPResponse, self.get("v1/user")) response = self._server.handle_bad_response(response) return response def bootstrap(self) -> BootstrapOutputDTO | HTTPResponse: - response = cast(Union[BootstrapOutputDTO, HTTPResponse], self.post("v1/bootstrap")) + response = cast(BootstrapOutputDTO | HTTPResponse, self.post("v1/bootstrap")) # Connect versions before 2024.05.0 only provide the experimental endpoint. The server version # is not exposed to unauthenticated requests, so fall back based on the 404 instead. if isinstance(response, HTTPResponse) and response.status == 404: - response = cast(Union[BootstrapOutputDTO, HTTPResponse], self.post("v1/experimental/bootstrap")) + response = cast(BootstrapOutputDTO | HTTPResponse, self.post("v1/experimental/bootstrap")) # TODO: The place where bootstrap() is called expects a JSON object if the response is successfule, and a # HTTPResponse if it is not; then it handles the error. This is different from the other methods, and probably # should be changed in the future. For this to work, we will _not_ call .handle_bad_response() here at present. @@ -602,7 +598,7 @@ def bootstrap(self) -> BootstrapOutputDTO | HTTPResponse: return response def server_settings(self) -> ServerSettings: - response = cast(Union[ServerSettings, HTTPResponse], self.get("server_settings")) + response = cast(ServerSettings | HTTPResponse, self.get("server_settings")) response = self._server.handle_bad_response(response) return response @@ -625,14 +621,14 @@ def server_version(self) -> str: return self.server_settings().get("version", "") def python_settings(self) -> PyInfo: - response = cast(Union[PyInfo, HTTPResponse], self.get("v1/server_settings/python")) + response = cast(PyInfo | HTTPResponse, self.get("v1/server_settings/python")) response = self._server.handle_bad_response(response) return response def nodejs_settings(self) -> dict[str, Any]: """Return Node.js availability and publishability information.""" response = self.get("v1/server_settings/nodejs") - return cast(typing.Dict[str, Any], self._server.handle_bad_response(response)) + return cast(dict[str, Any], self._server.handle_bad_response(response)) def add_environment_vars(self, content_guid: str, env_vars: list[tuple[str, str]]): env_body = [dict(name=kv[0], value=kv[1]) for kv in env_vars] @@ -641,7 +637,7 @@ def add_environment_vars(self, content_guid: str, env_vars: list[tuple[str, str] def is_failed_response(self, response: HTTPResponse | JsonData) -> bool: return isinstance(response, HTTPResponse) and response.status is not None and response.status >= 500 - def access_content(self, content_guid: str, bundle_id: Optional[str] = None) -> None: + def access_content(self, content_guid: str, bundle_id: str | None = None) -> None: method = "GET" base = dirname(self._url.path).rstrip("/") # strip "__api__" and any trailing slash # Access a specific (e.g. draft, not-yet-activated) bundle's preview URL when a @@ -678,23 +674,23 @@ def content_lockfile(self, content_guid: str) -> HTTPResponse: response = self._server.handle_bad_response(response, is_httpresponse=True) return response - def content_list(self, filters: Optional[Mapping[str, JsonData]] = None) -> list[ContentItemV1]: - response = cast(Union[List[ContentItemV1], HTTPResponse], self.get("v1/content", query_params=filters)) + def content_list(self, filters: Mapping[str, JsonData] | None = None) -> list[ContentItemV1]: + response = cast(list[ContentItemV1] | HTTPResponse, self.get("v1/content", query_params=filters)) response = self._server.handle_bad_response(response) return response def content_get(self, content_guid: str) -> ContentItemV1: - response = cast(Union[ContentItemV1, HTTPResponse], self.get(f"v1/content/{content_guid}")) + response = cast(ContentItemV1 | HTTPResponse, self.get(f"v1/content/{content_guid}")) response = self._server.handle_bad_response(response) return response def content_create(self, name: str) -> ContentItemV1: - response = cast(Union[ContentItemV1, HTTPResponse], self.post("v1/content", body={"name": name})) + response = cast(ContentItemV1 | HTTPResponse, self.post("v1/content", body={"name": name})) response = self._server.handle_bad_response(response) return response def upload_bundle( - self, content_guid: str, tarball: typing.IO[bytes], metadata: Optional[dict[str, str]] = None + self, content_guid: str, tarball: typing.IO[bytes], metadata: dict[str, str] | None = None ) -> BundleMetadata: """ Upload a bundle to the server. @@ -713,24 +709,22 @@ def upload_bundle( } body, content_type = create_multipart_form_data(fields) response = cast( - Union[BundleMetadata, HTTPResponse], + BundleMetadata | HTTPResponse, self.post(f"v1/content/{content_guid}/bundles", body=body, headers={"Content-Type": content_type}), ) else: response = cast( - Union[BundleMetadata, HTTPResponse], self.post(f"v1/content/{content_guid}/bundles", body=tarball) + BundleMetadata | HTTPResponse, self.post(f"v1/content/{content_guid}/bundles", body=tarball) ) response = self._server.handle_bad_response(response) return response def content_update(self, content_guid: str, updates: Mapping[str, str | None]) -> ContentItemV1: - response = cast(Union[ContentItemV1, HTTPResponse], self.patch(f"v1/content/{content_guid}", body=updates)) + response = cast(ContentItemV1 | HTTPResponse, self.patch(f"v1/content/{content_guid}", body=updates)) response = self._server.handle_bad_response(response) return response - def content_build( - self, content_guid: str, bundle_id: Optional[str] = None, activate: bool = True - ) -> BuildOutputDTO: + def content_build(self, content_guid: str, bundle_id: str | None = None, activate: bool = True) -> BuildOutputDTO: body: dict[str, str | bool | None] = {"bundle_id": bundle_id} if not activate: # The default behavior is to activate the app after building. @@ -738,15 +732,13 @@ def content_build( # That way we can keep the API backwards compatible. body["activate"] = False response = cast( - Union[BuildOutputDTO, HTTPResponse], + BuildOutputDTO | HTTPResponse, self.post(f"v1/content/{content_guid}/build", body=body), ) response = self._server.handle_bad_response(response) return response - def content_deploy( - self, content_guid: str, bundle_id: Optional[str] = None, activate: bool = True - ) -> BuildOutputDTO: + def content_deploy(self, content_guid: str, bundle_id: str | None = None, activate: bool = True) -> BuildOutputDTO: body: dict[str, str | bool | None] = {"bundle_id": bundle_id} if not activate: # The default behavior is to activate the app after deploying. @@ -754,13 +746,13 @@ def content_deploy( # That way we can keep the API backwards compatible. body["activate"] = False response = cast( - Union[BuildOutputDTO, HTTPResponse], + BuildOutputDTO | HTTPResponse, self.post(f"v1/content/{content_guid}/deploy", body=body), ) response = self._server.handle_bad_response(response) return response - def get_repository(self, content_guid: str) -> Optional[RepositoryInfo]: + def get_repository(self, content_guid: str) -> RepositoryInfo | None: """Get git repository configuration for a content item. :param content_guid: The GUID of the content item @@ -798,7 +790,7 @@ def set_repository( "polling": polling, } response = cast( - Union[RepositoryInfo, HTTPResponse], + RepositoryInfo | HTTPResponse, self.put("v1/content/%s/repository" % content_guid, body=body), ) response = self._server.handle_bad_response(response) @@ -807,10 +799,10 @@ def set_repository( def update_repository( self, content_guid: str, - repository: Optional[str] = None, - branch: Optional[str] = None, - directory: Optional[str] = None, - polling: Optional[bool] = None, + repository: str | None = None, + branch: str | None = None, + directory: str | None = None, + polling: bool | None = None, ) -> RepositoryInfo: """Partially update git repository configuration for a content item. @@ -834,7 +826,7 @@ def update_repository( body["polling"] = polling response = cast( - Union[RepositoryInfo, HTTPResponse], + RepositoryInfo | HTTPResponse, self.patch("v1/content/%s/repository" % content_guid, body=body), ) response = self._server.handle_bad_response(response) @@ -852,9 +844,9 @@ def delete_repository(self, content_guid: str) -> None: def create_bundle_from_repository( self, content_guid: str, - repository: Optional[str] = None, - ref: Optional[str] = None, - directory: Optional[str] = None, + repository: str | None = None, + ref: str | None = None, + directory: str | None = None, ) -> RepositoryBundleOutput: """Create a bundle from a git repository location. @@ -877,7 +869,7 @@ def create_bundle_from_repository( body["directory"] = directory response = cast( - Union[RepositoryBundleOutput, HTTPResponse], + RepositoryBundleOutput | HTTPResponse, self.post("v1/content/%s/repository/bundle" % content_guid, body=body), ) response = self._server.handle_bad_response(response) @@ -885,13 +877,13 @@ def create_bundle_from_repository( def deploy_git( self, - app_id: Optional[str], + app_id: str | None, name: str, repository: str, branch: str, subdirectory: str, - title: Optional[str], - env_vars: Optional[dict[str, str]], + title: str | None, + env_vars: dict[str, str] | None, polling: bool = True, activate: bool = True, ) -> RSConnectClientDeployResult: @@ -981,32 +973,32 @@ def deploy_git( ) def system_caches_runtime_list(self) -> list[ListEntryOutputDTO]: - response = cast(Union[List[ListEntryOutputDTO], HTTPResponse], self.get("v1/system/caches/runtime")) + response = cast(list[ListEntryOutputDTO] | HTTPResponse, self.get("v1/system/caches/runtime")) response = self._server.handle_bad_response(response) return response def system_caches_runtime_delete(self, target: DeleteInputDTO) -> DeleteOutputDTO: - response = cast(Union[DeleteOutputDTO, HTTPResponse], self.delete("v1/system/caches/runtime", body=target)) + response = cast(DeleteOutputDTO | HTTPResponse, self.delete("v1/system/caches/runtime", body=target)) response = self._server.handle_bad_response(response) return response def environment_list(self) -> list[EnvironmentV1]: - response = cast(Union[List[EnvironmentV1], HTTPResponse], self.get("v1/environments")) + response = cast(list[EnvironmentV1] | HTTPResponse, self.get("v1/environments")) response = self._server.handle_bad_response(response) return response def environment_get(self, guid: str) -> EnvironmentV1: - response = cast(Union[EnvironmentV1, HTTPResponse], self.get(f"v1/environments/{guid}")) + response = cast(EnvironmentV1 | HTTPResponse, self.get(f"v1/environments/{guid}")) response = self._server.handle_bad_response(response) return response def environment_create(self, body: EnvironmentCreateInput) -> EnvironmentV1: - response = cast(Union[EnvironmentV1, HTTPResponse], self.post("v1/environments", body=body)) + response = cast(EnvironmentV1 | HTTPResponse, self.post("v1/environments", body=body)) response = self._server.handle_bad_response(response) return response def environment_update(self, guid: str, body: EnvironmentUpdateInput) -> EnvironmentV1: - response = cast(Union[EnvironmentV1, HTTPResponse], self.put(f"v1/environments/{guid}", body=body)) + response = cast(EnvironmentV1 | HTTPResponse, self.put(f"v1/environments/{guid}", body=body)) response = self._server.handle_bad_response(response) return response @@ -1016,7 +1008,7 @@ def environment_delete(self, guid: str) -> None: def environment_permission_list(self, env_guid: str) -> list[EnvironmentPermissionV1]: response = cast( - Union[List[EnvironmentPermissionV1], HTTPResponse], + list[EnvironmentPermissionV1] | HTTPResponse, self.get(f"v1/environments/{env_guid}/permissions"), ) response = self._server.handle_bad_response(response) @@ -1024,7 +1016,7 @@ def environment_permission_list(self, env_guid: str) -> list[EnvironmentPermissi def environment_permission_add(self, env_guid: str, body: EnvironmentPermissionInput) -> EnvironmentPermissionV1: response = cast( - Union[EnvironmentPermissionV1, HTTPResponse], + EnvironmentPermissionV1 | HTTPResponse, self.post(f"v1/environments/{env_guid}/permissions", body=body), ) response = self._server.handle_bad_response(response) @@ -1038,22 +1030,22 @@ def environment_permission_delete(self, env_guid: str, permission_guid: str) -> self._server.handle_bad_response(response, is_httpresponse=True) def oauth_integration_list(self) -> list[OAuthIntegration]: - response = cast(Union[List[OAuthIntegration], HTTPResponse], self.get("v1/oauth/integrations")) + response = cast(list[OAuthIntegration] | HTTPResponse, self.get("v1/oauth/integrations")) response = self._server.handle_bad_response(response) return response def oauth_integration_get(self, guid: str) -> OAuthIntegration: - response = cast(Union[OAuthIntegration, HTTPResponse], self.get(f"v1/oauth/integrations/{guid}")) + response = cast(OAuthIntegration | HTTPResponse, self.get(f"v1/oauth/integrations/{guid}")) response = self._server.handle_bad_response(response) return response def oauth_integration_create(self, body: OAuthIntegrationInput) -> OAuthIntegration: - response = cast(Union[OAuthIntegration, HTTPResponse], self.post("v1/oauth/integrations", body=body)) + response = cast(OAuthIntegration | HTTPResponse, self.post("v1/oauth/integrations", body=body)) response = self._server.handle_bad_response(response) return response def oauth_integration_update(self, guid: str, body: OAuthIntegrationUpdate) -> OAuthIntegration: - response = cast(Union[OAuthIntegration, HTTPResponse], self.patch(f"v1/oauth/integrations/{guid}", body=body)) + response = cast(OAuthIntegration | HTTPResponse, self.patch(f"v1/oauth/integrations/{guid}", body=body)) response = self._server.handle_bad_response(response) return response @@ -1062,20 +1054,20 @@ def oauth_integration_delete(self, guid: str) -> None: self._server.handle_bad_response(response, is_httpresponse=True) def oauth_template_list(self) -> list[OAuthTemplate]: - response = cast(Union[List[OAuthTemplate], HTTPResponse], self.get("v1/oauth/templates")) + response = cast(list[OAuthTemplate] | HTTPResponse, self.get("v1/oauth/templates")) response = self._server.handle_bad_response(response) return response def oauth_template_get(self, key: str) -> OAuthTemplate: - response = cast(Union[OAuthTemplate, HTTPResponse], self.get(f"v1/oauth/templates/{key}")) + response = cast(OAuthTemplate | HTTPResponse, self.get(f"v1/oauth/templates/{key}")) response = self._server.handle_bad_response(response) return response def task_get( self, task_id: str, - first: Optional[int] = None, - wait: Optional[int] = None, + first: int | None = None, + wait: int | None = None, ) -> TaskStatusV1: params = None if first is not None or wait is not None: @@ -1084,7 +1076,7 @@ def task_get( params["first"] = first if wait is not None: params["wait"] = wait - response = cast(Union[TaskStatusV1, HTTPResponse], self.get(f"v1/tasks/{task_id}", query_params=params)) + response = cast(TaskStatusV1 | HTTPResponse, self.get(f"v1/tasks/{task_id}", query_params=params)) response = self._server.handle_bad_response(response) # compatibility with rsconnect-jupyter @@ -1095,14 +1087,14 @@ def task_get( def deploy( self, - app_id: Optional[str], - app_name: Optional[str], - app_title: Optional[str], + app_id: str | None, + app_name: str | None, + app_title: str | None, title_is_default: bool, tarball: IO[bytes], - env_vars: Optional[dict[str, str]] = None, + env_vars: dict[str, str] | None = None, activate: bool = True, - metadata: Optional[dict[str, str]] = None, + metadata: dict[str, str] | None = None, ) -> RSConnectClientDeployResult: if app_id is None: if app_name is None: @@ -1161,7 +1153,7 @@ def get_content(self, content_guid: str) -> ContentItemV1: def wait_for_task( self, task_id: str, - log_callback: Optional[Callable[[str], None]], + log_callback: Callable[[str], None] | None, abort_func: Callable[[], bool] = lambda: False, timeout: int = get_task_timeout(), poll_wait: int = 1, @@ -1230,9 +1222,9 @@ class RecordTarget(NamedTuple): name: str # An account id or legacy name, resolved against Connect Cloud before deploy. - record_account: Optional[str] + record_account: str | None # The saved credential's account name, when the record key matches it. - saved_account: Optional[str] + saved_account: str | None # Reported only after the current options accept the inferred target. description: str @@ -1283,42 +1275,42 @@ def _is_shinyapps_record(record: AppMetadata) -> bool: class RSConnectExecutor: def __init__( self, - ctx: Optional[click.Context] = None, - name: Optional[str] = None, - url: Optional[str] = None, - api_key: Optional[str] = None, - snowflake_connection_name: Optional[str] = None, + ctx: click.Context | None = None, + name: str | None = None, + url: str | None = None, + api_key: str | None = None, + snowflake_connection_name: str | None = None, insecure: bool = False, - cacert: Optional[str] = None, - ca_data: Optional[str | bytes] = None, - cookies: Optional[CookieJar] = None, - account: Optional[str] = None, - token: Optional[str] = None, - secret: Optional[str] = None, + cacert: str | None = None, + ca_data: str | bytes | None = None, + cookies: CookieJar | None = None, + account: str | None = None, + token: str | None = None, + secret: str | None = None, timeout: int = 30, - logger: Optional[logging.Logger] = console_logger, + logger: logging.Logger | None = console_logger, *, - client_id: Optional[str] = None, - client_secret: Optional[str] = None, + client_id: str | None = None, + client_secret: str | None = None, use_connect_cloud: bool = False, - path: Optional[str] = None, - server: Optional[str] = None, - exclude: Optional[tuple[str, ...]] = None, - new: Optional[bool] = None, - app_id: Optional[str] = None, - title: Optional[str] = None, - title_is_default: Optional[bool] = None, - visibility: Optional[str] = None, - disable_env_management: Optional[bool] = None, - env_vars: Optional[dict[str, str]] = None, - metadata: Optional[dict[str, str]] = None, - repository: Optional[str] = None, - branch: Optional[str] = None, - subdirectory: Optional[str] = None, + path: str | None = None, + server: str | None = None, + exclude: tuple[str, ...] | None = None, + new: bool | None = None, + app_id: str | None = None, + title: str | None = None, + title_is_default: bool | None = None, + visibility: str | None = None, + disable_env_management: bool | None = None, + env_vars: dict[str, str] | None = None, + metadata: dict[str, str] | None = None, + repository: str | None = None, + branch: str | None = None, + subdirectory: str | None = None, polling: bool = True, - quarto_inputs: Optional[List[str]] = None, - infer_target: Optional[bool] = None, - app_store: Optional[AppStore] = None, + quarto_inputs: list[str] | None = None, + infer_target: bool | None = None, + app_store: AppStore | None = None, ) -> None: self.remote_server: TargetableServer self.client: RSConnectClient | PositClient | ConnectCloudClient @@ -1368,7 +1360,7 @@ def __init__( self.logger: logging.Logger | None = logger self.ctx = ctx # Connect Cloud account state carried from inference through validation. - self.record_account: Optional[str] = None + self.record_account: str | None = None self.record_account_named: bool = False self.setup_remote_server( ctx=ctx, @@ -1397,27 +1389,27 @@ def __init__( def fromConnectServer( cls, connect_server: RSConnectServer, - ctx: Optional[click.Context] = None, - cookies: Optional[CookieJar] = None, - account: Optional[str] = None, - token: Optional[str] = None, - secret: Optional[str] = None, + ctx: click.Context | None = None, + cookies: CookieJar | None = None, + account: str | None = None, + token: str | None = None, + secret: str | None = None, timeout: int = 30, - logger: Optional[logging.Logger] = console_logger, + logger: logging.Logger | None = console_logger, *, - path: Optional[str] = None, - server: Optional[str] = None, - exclude: Optional[tuple[str, ...]] = None, - new: Optional[bool] = None, - app_id: Optional[str] = None, - title: Optional[str] = None, - visibility: Optional[str] = None, - disable_env_management: Optional[bool] = None, - env_vars: Optional[dict[str, str]] = None, - metadata: Optional[dict[str, str]] = None, - repository: Optional[str] = None, - branch: Optional[str] = None, - subdirectory: Optional[str] = None, + path: str | None = None, + server: str | None = None, + exclude: tuple[str, ...] | None = None, + new: bool | None = None, + app_id: str | None = None, + title: str | None = None, + visibility: str | None = None, + disable_env_management: bool | None = None, + env_vars: dict[str, str] | None = None, + metadata: dict[str, str] | None = None, + repository: str | None = None, + branch: str | None = None, + subdirectory: str | None = None, polling: bool = True, ): return cls( @@ -1508,7 +1500,7 @@ def _target_required_error(decline_reason: str, remedy: str = _NAME_A_TARGET) -> def _target_from_deployment_record( self, store: ServerStore - ) -> tuple[Optional[RecordTarget], Optional[RSConnectException]]: + ) -> tuple[RecordTarget | None, RSConnectException | None]: """Infer a target from the directory's sole deployment record. Returns either a target or the reason existing history cannot be used. @@ -1577,19 +1569,19 @@ def _target_from_deployment_record( def setup_remote_server( self, - ctx: Optional[click.Context], - name: Optional[str] = None, - url: Optional[str] = None, - api_key: Optional[str] = None, - snowflake_connection_name: Optional[str] = None, + ctx: click.Context | None, + name: str | None = None, + url: str | None = None, + api_key: str | None = None, + snowflake_connection_name: str | None = None, insecure: bool = False, - cacert: Optional[str] = None, - ca_data: Optional[str | bytes] = None, - account_name: Optional[str] = None, - token: Optional[str] = None, - secret: Optional[str] = None, - client_id: Optional[str] = None, - client_secret: Optional[str] = None, + cacert: str | None = None, + ca_data: str | bytes | None = None, + account_name: str | None = None, + token: str | None = None, + secret: str | None = None, + client_id: str | None = None, + client_secret: str | None = None, use_connect_cloud: bool = False, infer_target: bool = False, ): @@ -1952,7 +1944,7 @@ def _source(param: str) -> str: "Pass -s/--server or -n/--name to deploy elsewhere." % inferred_description ) - def setup_client(self, cookies: Optional[CookieJar] = None): + def setup_client(self, cookies: CookieJar | None = None): if isinstance(self.remote_server, RSConnectServer): self.client = RSConnectClient(self.remote_server, cookies) elif isinstance(self.remote_server, SPCSConnectServer): @@ -2085,7 +2077,7 @@ def validate_posit_server(self): result = client.get_current_user() result = server.handle_bad_response(result) except RSConnectException as exc: - raise RSConnectException("Failed to verify with {} ({}).".format(server.remote_name, exc)) + raise RSConnectException(f"Failed to verify with {server.remote_name} ({exc}).") @cls_logged("Making bundle ...") def make_bundle( @@ -2104,7 +2096,7 @@ def make_bundle( try: self.bundle = func(*args, **kwargs) - except IOError as error: + except OSError as error: msg = "Unable to include the file %s in the bundle: %s" % ( error.filename, error.args[1], @@ -2154,7 +2146,7 @@ def bundle_manifest(self) -> dict[str, Any]: finally: self.bundle.seek(position) - def python_version_for_connect_cloud(self) -> Optional[str]: + def python_version_for_connect_cloud(self) -> str | None: """The MAJOR.MINOR Python version to ask Connect Cloud for, or None. None means the request omits the field: a redeploy keeps the version already @@ -2165,8 +2157,8 @@ def python_version_for_connect_cloud(self) -> Optional[str]: environment: dict[str, Any] = manifest.get("environment") or {} requirement: dict[str, Any] = environment.get("python") or {} interpreter: dict[str, Any] = manifest.get("python") or {} - requires: Optional[str] = requirement.get("requires") - local_version: Optional[str] = interpreter.get("version") + requires: str | None = requirement.get("requires") + local_version: str | None = interpreter.get("version") return connect_cloud.resolve_python_version(requires, local_version) def primary_file_for_connect_cloud(self) -> str: @@ -2467,7 +2459,7 @@ def record_server_key(self) -> str: return "%s#%s" % (self.remote_server.url, account) return self.remote_server.url - def record_server_key_fallback(self) -> Optional[str]: + def record_server_key_fallback(self) -> str | None: """The name-keyed record location, for records written before an account id was known. Consulted on reads when the id-keyed lookup finds nothing; writes always use record_server_key, which migrates the record.""" @@ -2505,7 +2497,7 @@ def write_deployed_info(self): ): self.app_store.remove(fallback_key) - def migration_source_record(self, from_server: Optional[str] = None) -> Optional[AppMetadata]: + def migration_source_record(self, from_server: str | None = None) -> AppMetadata | None: """The deployment record being migrated away from, if there is one. Supplies the title and app mode for the new record, and is removed only @@ -2553,7 +2545,7 @@ def migration_source_record(self, from_server: Optional[str] = None) -> Optional def migrate_to_connect_cloud( self, content_id: str, - from_server: Optional[str] = None, + from_server: str | None = None, overwrite: bool = False, ) -> AppMetadata: """Point this content's local deployment record at existing Posit Connect Cloud content. @@ -2877,7 +2869,7 @@ def server_settings(self): raise RSConnectException("There is an SSL/TLS configuration problem: %s" % ssl_error) return result - def verify_api_key(self, server: Optional[RSConnectServer] = None): + def verify_api_key(self, server: RSConnectServer | None = None): """ Verify that an API Key may be used to authenticate with the given Posit Connect server. """ @@ -3117,7 +3109,7 @@ def _tweak_response(self, response: HTTPResponse) -> JsonData | HTTPResponse: def get_extra_headers(self, url: str, method: str, body: str | bytes): canonical_request_method = method.upper() canonical_request_path = parse.urlparse(url).path - canonical_request_date = datetime.datetime.now(datetime.timezone.utc).strftime("%a, %d %b %Y %H:%M:%S GMT") + canonical_request_date = datetime.datetime.now(datetime.UTC).strftime("%a, %d %b %Y %H:%M:%S GMT") # get request checksum md5 = hashlib.md5() @@ -3140,7 +3132,7 @@ def get_extra_headers(self, url: str, method: str, body: str | bytes): } def get_application(self, application_id: str): - response = cast(Union[PositClientApp, HTTPResponse], self.get(f"/v1/applications/{application_id}")) + response = cast(PositClientApp | HTTPResponse, self.get(f"/v1/applications/{application_id}")) response = self._server.handle_bad_response(response) return response @@ -3158,18 +3150,18 @@ def create_application(self, account_id: int, application_name: str) -> PositCli "name": application_name, "template": "shiny", } - response = cast(Union[PositClientApp, HTTPResponse], self.post("/v1/applications/", body=application_data)) + response = cast(PositClientApp | HTTPResponse, self.post("/v1/applications/", body=application_data)) response = self._server.handle_bad_response(response) return response def get_accounts(self) -> PositClientAccountSearchResults: - response = cast(Union[PositClientAccountSearchResults, HTTPResponse], self.get("/v1/accounts/")) + response = cast(PositClientAccountSearchResults | HTTPResponse, self.get("/v1/accounts/")) response = self._server.handle_bad_response(response) return response def _get_applications_like_name_page(self, name: str, offset: int) -> PositClientAppSearchResults: response = cast( - Union[PositClientAppSearchResults, HTTPResponse], + PositClientAppSearchResults | HTTPResponse, self.get(f"/v1/applications?filter=name:like:{name}&offset={offset}&count=100&use_advanced_filters=true"), ) response = self._server.handle_bad_response(response) @@ -3184,7 +3176,7 @@ def create_bundle( "content_length": content_length, "checksum": checksum, } - response = cast(Union[PositClientBundle, HTTPResponse], self.post("/v1/bundles", body=bundle_data)) + response = cast(PositClientBundle | HTTPResponse, self.post("/v1/bundles", body=bundle_data)) response = self._server.handle_bad_response(response) return response @@ -3195,7 +3187,7 @@ def set_bundle_status(self, bundle_id: str, bundle_status: str): def deploy_application(self, bundle_id: str, app_id: str) -> PositClientDeployTask: response = cast( - Union[PositClientDeployTask, HTTPResponse], + PositClientDeployTask | HTTPResponse, self.post(f"/v1/applications/{app_id}/deploy", body={"bundle": bundle_id, "rebuild": False}), ) response = self._server.handle_bad_response(response) @@ -3203,7 +3195,7 @@ def deploy_application(self, bundle_id: str, app_id: str) -> PositClientDeployTa def get_task(self, task_id: str) -> PositClientDeployTask: response = cast( - Union[PositClientDeployTask, HTTPResponse], + PositClientDeployTask | HTTPResponse, self.get(f"/v1/tasks/{task_id}", query_params={"legacy": "true"}), ) response = self._server.handle_bad_response(response) @@ -3211,7 +3203,7 @@ def get_task(self, task_id: str) -> PositClientDeployTask: def get_shinyapps_build_task(self, parent_task_id: str) -> PositClientShinyappsBuildTaskSearchResults: response = cast( - Union[PositClientShinyappsBuildTaskSearchResults, HTTPResponse], + PositClientShinyappsBuildTaskSearchResults | HTTPResponse, self.get( "/v1/tasks", query_params={ @@ -3303,7 +3295,7 @@ class ConnectCloudAccount(TypedDict): id: str name: str permissions: NotRequired[list[str]] - role: NotRequired[Optional[str]] + role: NotRequired[str | None] sso_enabled: NotRequired[bool] @@ -3315,12 +3307,12 @@ class ConnectCloudAccountSearchResults(TypedDict): class ConnectCloudRevision(TypedDict): id: str content_id: NotRequired[str] - python_version: NotRequired[Optional[str]] + python_version: NotRequired[str | None] status: NotRequired[str] source_bundle_upload_url: NotRequired[str] - publish_result: NotRequired[Optional[str]] - publish_error_details: NotRequired[Optional[str]] - publish_log_channel: NotRequired[Optional[str]] + publish_result: NotRequired[str | None] + publish_error_details: NotRequired[str | None] + publish_log_channel: NotRequired[str | None] class ConnectCloudContent(TypedDict): @@ -3328,8 +3320,8 @@ class ConnectCloudContent(TypedDict): account_id: NotRequired[str] title: NotRequired[str] state: NotRequired[str] - next_revision: NotRequired[Optional[ConnectCloudRevision]] - current_revision: NotRequired[Optional[ConnectCloudRevision]] + next_revision: NotRequired[ConnectCloudRevision | None] + current_revision: NotRequired[ConnectCloudRevision | None] class ConnectCloudLogEntry(TypedDict): @@ -3486,7 +3478,7 @@ def _add_command(self, service_account: bool = False) -> str: parts.append("--client-id --client-secret ") return " ".join(parts) - def _persist_tokens(self, access_token: Optional[str], refresh_token: Optional[str]) -> None: + def _persist_tokens(self, access_token: str | None, refresh_token: str | None) -> None: """Write the tokens back to the saved credential, or clear them when both are None. Prefers the system keyring, falling back to the tokens' fields in @@ -3563,7 +3555,7 @@ def get_accounts(self) -> list[ConnectCloudAccount]: offset = 0 for _ in range(_CONNECT_CLOUD_MAX_ACCOUNT_PAGES): response = cast( - Union[ConnectCloudAccountSearchResults, HTTPResponse], + ConnectCloudAccountSearchResults | HTTPResponse, self.get( "/accounts", query_params={ @@ -3668,7 +3660,7 @@ def _can_publish(account: ConnectCloudAccount) -> bool: return _CONNECT_CLOUD_PUBLISH_PERMISSION in permissions @staticmethod - def _sso_blocked_error(server: ConnectCloudServer, account: ConnectCloudAccount) -> Optional[RSConnectException]: + def _sso_blocked_error(server: ConnectCloudServer, account: ConnectCloudAccount) -> RSConnectException | None: """The error for client credentials that SSO keeps from publishing to this account, if that is why the account cannot be published to. @@ -3691,7 +3683,7 @@ def _sso_blocked_error(server: ConnectCloudServer, account: ConnectCloudAccount) ) def get_content(self, content_id: str) -> ConnectCloudContent: - response = cast(Union[ConnectCloudContent, HTTPResponse], self.get(f"/contents/{content_id}")) + response = cast(ConnectCloudContent | HTTPResponse, self.get(f"/contents/{content_id}")) content = self._server.handle_bad_response(response) if content.get("state") == "deleted": # The API reports deleted content as a normal 200. Surface it the way @@ -3709,9 +3701,9 @@ def create_content( content_type: str, app_mode: str, primary_file: str, - secrets: Optional[list[dict[str, str]]] = None, - access: Optional[str] = None, - python_version: Optional[str] = None, + secrets: list[dict[str, str]] | None = None, + access: str | None = None, + python_version: str | None = None, ) -> ConnectCloudContent: """Create content to upload a bundle into. @@ -3738,7 +3730,7 @@ def create_content( } if access is not None: body["access"] = access - response = cast(Union[ConnectCloudContent, HTTPResponse], self.post("/contents", body=body)) + response = cast(ConnectCloudContent | HTTPResponse, self.post("/contents", body=body)) return self._server.handle_bad_response(response) def update_content( @@ -3747,11 +3739,11 @@ def update_content( primary_file: str, app_mode: str, content_type: str, - secrets: Optional[list[dict[str, str]]] = None, + secrets: list[dict[str, str]] | None = None, new_bundle: bool = True, - title: Optional[str] = None, - access: Optional[str] = None, - python_version: Optional[str] = None, + title: str | None = None, + access: str | None = None, + python_version: str | None = None, ) -> ConnectCloudContent: """Update content, optionally minting a fresh revision to upload into. @@ -3786,7 +3778,7 @@ def update_content( body["access"] = access query_params: dict[str, JsonData] = {"new_bundle": "true"} if new_bundle else {} response = cast( - Union[ConnectCloudContent, HTTPResponse], + ConnectCloudContent | HTTPResponse, self.patch(f"/contents/{content_id}", query_params=query_params, body=body), ) return self._server.handle_bad_response(response) @@ -3796,7 +3788,7 @@ def publish(self, content_id: str) -> HTTPResponse: return self._server.handle_bad_response(response, is_httpresponse=True) def get_revision(self, revision_id: str) -> ConnectCloudRevision: - response = cast(Union[ConnectCloudRevision, HTTPResponse], self.get(f"/revisions/{revision_id}")) + response = cast(ConnectCloudRevision | HTTPResponse, self.get(f"/revisions/{revision_id}")) return self._server.handle_bad_response(response) def authorize_log_channel(self, channel: str) -> str: @@ -3806,7 +3798,7 @@ def authorize_log_channel(self, channel: str) -> str: "resource_id": channel, "permission": "revision.logs:read", } - response = cast(Union[ConnectCloudAuthorization, HTTPResponse], self.post("/authorization", body=body)) + response = cast(ConnectCloudAuthorization | HTTPResponse, self.post("/authorization", body=body)) data = self._server.handle_bad_response(response) token = data.get("token") if not token: @@ -3868,11 +3860,11 @@ def __init__(self, posit_client: PositClient, server: ShinyappsServer): def prepare_deploy( self, - app_id: Optional[str], + app_id: str | None, app_name: str, bundle_size: int, bundle_hash: str, - visibility: Optional[str], + visibility: str | None, ): accounts = self._posit_client.get_accounts() accounts = self._server.handle_bad_response(accounts) @@ -3926,7 +3918,7 @@ def do_deploy(self, bundle_id: str, app_id: str): class ConnectCloudDeployResult: - def __init__(self, content_id: str, revision_id: str, upload_url: Optional[str], app_url: str, title: str): + def __init__(self, content_id: str, revision_id: str, upload_url: str | None, app_url: str, title: str): self.content_id = content_id self.revision_id = revision_id self.upload_url = upload_url @@ -3962,17 +3954,17 @@ def __init__(self, client: ConnectCloudClient, server: ConnectCloudServer): def prepare_deploy( self, - app_id: Optional[str], + app_id: str | None, app_name: str, title: str, app_mode: AppMode, primary_file: str, - env_vars: Optional[dict[str, str]] = None, + env_vars: dict[str, str] | None = None, upload: bool = True, update_title: bool = False, app_id_is_explicit: bool = False, - visibility: Optional[str] = None, - python_version: Optional[str] = None, + visibility: str | None = None, + python_version: str | None = None, ) -> ConnectCloudDeployResult: """Create or fetch the content item and get a revision to upload into. @@ -3999,7 +3991,7 @@ def prepare_deploy( # replaces the whole collection, matching the R client. secrets = [{"name": name, "value": value} for name, value in env_vars.items()] if env_vars else None - content: Optional[ConnectCloudContent] = None + content: ConnectCloudContent | None = None if app_id: try: content = self._client.get_content(app_id) @@ -4086,7 +4078,7 @@ def account_id(self) -> str: account = self._client.get_account_by_name(self._server.account_name) return account["id"] - def account_for_id(self, account_id: str) -> Optional[ConnectCloudAccount]: + def account_for_id(self, account_id: str) -> ConnectCloudAccount | None: """The account with this id, among those the caller has a role on. None means the account is not one of them, which for content the caller is @@ -4097,7 +4089,7 @@ def account_for_id(self, account_id: str) -> Optional[ConnectCloudAccount]: return account return None - def account_name_for_id(self, account_id: str) -> Optional[str]: + def account_name_for_id(self, account_id: str) -> str | None: """The name of the account with this id, or None if the caller has no role on it.""" account = self.account_for_id(account_id) return account["name"] if account else None @@ -4112,13 +4104,13 @@ def can_publish_to(account: ConnectCloudAccount) -> bool: """ return ConnectCloudClient._can_publish(account) - def sso_blocked_error(self, account: ConnectCloudAccount) -> Optional[RSConnectException]: + def sso_blocked_error(self, account: ConnectCloudAccount) -> RSConnectException | None: """The error get_account_by_name raises when SSO keeps client credentials from publishing to this account, or None when that is not why publishing is refused. """ return ConnectCloudClient._sso_blocked_error(self._server, account) - def content_url(self, content_id: str, account_id: Optional[str]) -> str: + def content_url(self, content_id: str, account_id: str | None) -> str: """Build the browsable URL for a content item. The API returns only an account id, so the owning account has to be @@ -4142,19 +4134,19 @@ def upload_bundle(self, result: ConnectCloudDeployResult, contents: bytes) -> No raise RSConnectException("Posit Connect Cloud did not provide a bundle upload URL.") self._client.upload_bundle(result.upload_url, contents) - def do_deploy(self, result: ConnectCloudDeployResult, timeout: Optional[int] = None) -> None: + def do_deploy(self, result: ConnectCloudDeployResult, timeout: int | None = None) -> None: """Publish the uploaded revision and wait for it to finish.""" self._client.publish(result.content_id) self.wait_for_publish(result.revision_id, timeout=timeout) - def wait_for_publish(self, revision_id: str, timeout: Optional[int] = None) -> ConnectCloudRevision: + def wait_for_publish(self, revision_id: str, timeout: int | None = None) -> ConnectCloudRevision: """Poll a revision until it reports a publish result. Unlike the R client this has a timeout, and tolerates states it does not recognize rather than failing on them. """ deadline = None if timeout is None else time.time() + timeout - last_status: Optional[str] = None + last_status: str | None = None while True: revision = self._client.get_revision(revision_id) @@ -4203,7 +4195,7 @@ def _report_publish_failure(self, revision: ConnectCloudRevision) -> None: timestamp = entry.get("timestamp") if timestamp: # Connect Cloud reports microseconds since the epoch. - stamp = datetime.datetime.fromtimestamp(timestamp / 1e6, datetime.timezone.utc) + stamp = datetime.datetime.fromtimestamp(timestamp / 1e6, datetime.UTC) logger.error("%s %s" % (stamp.isoformat(), message)) else: logger.error(message) @@ -4229,7 +4221,7 @@ def verify_server(connect_server: RSConnectServer): raise RSConnectException("There is an SSL/TLS configuration problem: %s" % ssl_error) -def verify_api_key_response(client: RSConnectClient) -> Optional[UserRecord]: +def verify_api_key_response(client: RSConnectClient) -> UserRecord | None: """ Issue GET v1/user and interpret the response for the purpose of API key verification. @@ -4275,7 +4267,7 @@ def verify_api_key(connect_server: RSConnectServer) -> str: return user["username"] if user else "" -def get_python_info(connect_server: Union[RSConnectServer, SPCSConnectServer]): +def get_python_info(connect_server: RSConnectServer | SPCSConnectServer): """ Return information about versions of Python that are installed on the indicated Connect server. @@ -4295,10 +4287,10 @@ def get_posit_app_info(server: PositServer, app_id: str): def emit_task_log( - connect_server: Union[RSConnectServer, SPCSConnectServer], + connect_server: RSConnectServer | SPCSConnectServer, app_id: str, task_id: str, - log_callback: Optional[Callable[[str], None]], + log_callback: Callable[[str], None] | None, abort_func: Callable[[], bool] = lambda: False, timeout: int = get_task_timeout(), poll_wait: int = 1, diff --git a/rsconnect/bundle.py b/rsconnect/bundle.py index cad969f8e..41222622f 100644 --- a/rsconnect/bundle.py +++ b/rsconnect/bundle.py @@ -33,16 +33,12 @@ from typing import ( IO, TYPE_CHECKING, - Callable, - Iterator, Literal, NotRequired, - Optional, - Sequence, TypedDict, - Union, cast, ) +from collections.abc import Callable, Iterator, Sequence from urllib.parse import urlsplit from . import metadata @@ -236,18 +232,18 @@ class ManifestData(TypedDict): class Manifest: def __init__( self, - version: Optional[int] = None, - environment: Optional[Environment] = None, - r_environment: Optional[REnvironment] = None, - app_mode: Optional[AppMode] = None, - entrypoint: Optional[str] = None, - quarto_inspection: Optional[QuartoInspectResult] = None, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - primary_html: Optional[str] = None, - metadata: Optional[ManifestDataMetadata] = None, - files: Optional[dict[str, ManifestDataFile]] = None, + version: int | None = None, + environment: Environment | None = None, + r_environment: REnvironment | None = None, + app_mode: AppMode | None = None, + entrypoint: str | None = None, + quarto_inspection: QuartoInspectResult | None = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + primary_html: str | None = None, + metadata: ManifestDataMetadata | None = None, + files: dict[str, ManifestDataFile] | None = None, ) -> None: self.data: ManifestData = cast(ManifestData, {}) self.buffer: dict[str, str] = {} @@ -489,13 +485,13 @@ def discard_from_buffer(self, key: str): # noinspection SpellCheckingInspection def make_source_manifest( app_mode: AppMode, - environment: Optional[Environment] = None, - entrypoint: Optional[str] = None, - quarto_inspection: Optional[QuartoInspectResult] = None, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + environment: Environment | None = None, + entrypoint: str | None = None, + quarto_inspection: QuartoInspectResult | None = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> ManifestData: manifest: Manifest = Manifest( app_mode=app_mode, @@ -613,9 +609,9 @@ def write_manifest( output_dir: str, hide_all_input: bool = False, hide_tagged_input: bool = False, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, ) -> tuple[list[str], list[str]]: """Create a manifest for source publishing the specified notebook. @@ -699,10 +695,10 @@ def make_notebook_source_bundle( extra_files: Sequence[str], hide_all_input: bool, hide_tagged_input: bool, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> IO[bytes]: """Create a bundle containing the specified notebook and python environment. @@ -769,13 +765,13 @@ def make_quarto_source_bundle( file_or_directory: str, inspect: QuartoInspectResult, app_mode: AppMode, - environment: Optional[Environment], + environment: Environment | None, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> typing.IO[bytes]: """ Create a bundle containing the specified Quarto content and (optional) @@ -958,7 +954,7 @@ def read_manifest_file(manifest_path: str | Path) -> tuple[ManifestData, str]: return manifest, raw_manifest -def _find_manifest_member(tar: tarfile.TarFile) -> Optional[tarfile.TarInfo]: +def _find_manifest_member(tar: tarfile.TarFile) -> tarfile.TarInfo | None: """ Locate the manifest.json member within a bundle tarball, mirroring the way Connect collapses single-subdirectory bundles when it extracts them. @@ -1127,10 +1123,10 @@ def make_api_manifest( environment: Environment, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> tuple[ManifestData, list[str]]: """ Makes a manifest for an API. @@ -1184,7 +1180,7 @@ def make_api_manifest( def create_html_manifest( path: str, - entrypoint: Optional[str], + entrypoint: str | None, extra_files: Sequence[str], excludes: Sequence[str], ) -> Manifest: @@ -1244,7 +1240,7 @@ def make_tensorflow_manifest( directory: str, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, + image: str | None = None, ) -> ManifestData: """ Creates and writes a manifest.json file for the given path. @@ -1277,7 +1273,7 @@ def make_tensorflow_manifest( def make_html_bundle( path: str, - entrypoint: Optional[str], + entrypoint: str | None, extra_files: Sequence[str], excludes: Sequence[str], ) -> typing.IO[bytes]: @@ -1323,7 +1319,7 @@ def make_tensorflow_bundle( directory: str, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, + image: str | None = None, ) -> typing.IO[bytes]: """ Create an html bundle, given a path and/or entrypoint. @@ -1483,7 +1479,7 @@ def infer_entrypoint_candidates(path: str, mimetype: str) -> list[str]: return mimetype_filelist[mimetype] or [] -def guess_deploy_dir(path: str | Path, entrypoint: Optional[str]) -> str: +def guess_deploy_dir(path: str | Path, entrypoint: str | None) -> str: if path and not exists(path): raise RSConnectException(f"Path {path} does not exist.") # The entrypoint is a bare basename meant to be resolved relative to ``path`` @@ -1563,15 +1559,15 @@ def abs_entrypoint(path: str | Path, entrypoint: str) -> str | None: def make_voila_bundle( path: str, - entrypoint: Optional[str], + entrypoint: str | None, extra_files: Sequence[str], excludes: Sequence[str], force_generate: bool, environment: Environment, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, multi_notebook: bool = False, ) -> typing.IO[bytes]: """ @@ -1637,10 +1633,10 @@ def make_api_bundle( environment: Environment, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> typing.IO[bytes]: """ Create an API bundle, given a directory path and a manifest. @@ -1692,8 +1688,8 @@ def make_nodejs_manifest( node_environment: NodeEnvironment, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_node: Optional[bool] = None, + image: str | None = None, + env_management_node: bool | None = None, ) -> tuple[ManifestData, list[str]]: """ Makes a manifest for a Node.js application. @@ -1758,8 +1754,8 @@ def make_nodejs_bundle( node_environment: NodeEnvironment, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_node: Optional[bool] = None, + image: str | None = None, + env_management_node: bool | None = None, ) -> typing.IO[bytes]: """ Create a Node.js application bundle, given a directory path. @@ -1828,13 +1824,13 @@ def make_quarto_manifest( file_or_directory: str, quarto_inspection: QuartoInspectResult, app_mode: AppMode, - environment: Optional[Environment], + environment: Environment | None, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> tuple[ManifestData, list[str]]: """ Makes a manifest for a Quarto project. @@ -1862,7 +1858,7 @@ def make_quarto_manifest( excludes = list(excludes or []) + [".quarto"] project_config = quarto_inspection.get("config", {}).get("project", {}) - output_dir = cast(Union[str, None], project_config.get("output-dir", None)) + output_dir = cast(str | None, project_config.get("output-dir", None)) if output_dir: excludes = excludes + [output_dir] @@ -2102,7 +2098,7 @@ def validate_node_entry_point(entry_point: str | None, directory: str) -> str: return entry_point -def _warn_on_ignored_entrypoint(entrypoint: Optional[str]) -> None: +def _warn_on_ignored_entrypoint(entrypoint: str | None) -> None: if entrypoint: warn_user(" Warning: entrypoint will not be used or considered for multi-notebook mode.") @@ -2115,9 +2111,9 @@ def create_notebook_manifest_and_environment_file( force: bool, hide_all_input: bool, hide_tagged_input: bool, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, ) -> None: """ Creates and writes a manifest.json file for the given notebook entry point file. @@ -2165,12 +2161,12 @@ def write_notebook_manifest_json( environment: Environment, app_mode: AppMode, extra_files: Sequence[str], - hide_all_input: Optional[bool], - hide_tagged_input: Optional[bool], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + hide_all_input: bool | None, + hide_tagged_input: bool | None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> bool: """ Creates and writes a manifest.json file for the given entry point file. If @@ -2252,15 +2248,15 @@ def write_notebook_manifest_json( def create_voila_manifest( path: str, - entrypoint: Optional[str], + entrypoint: str | None, environment: Environment, extra_files: Sequence[str], excludes: Sequence[str], force_generate: bool = True, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, multi_notebook: bool = False, ) -> Manifest: """ @@ -2344,15 +2340,15 @@ def create_voila_manifest( def write_voila_manifest_json( path: str, - entrypoint: Optional[str], + entrypoint: str | None, environment: Environment, extra_files: Sequence[str], excludes: Sequence[str], force_generate: bool = True, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, multi_notebook: bool = False, ) -> bool: """ @@ -2409,9 +2405,9 @@ def create_api_manifest_and_environment_file( extra_files: Sequence[str], excludes: Sequence[str], force: bool, - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, ) -> None: """ Creates and writes a manifest.json file for the given Python API entry point. If @@ -2458,10 +2454,10 @@ def write_api_manifest_json( app_mode: AppMode, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> bool: """ Creates and writes a manifest.json file for the given entry point file. If @@ -2510,8 +2506,8 @@ def write_nodejs_manifest_json( node_environment: NodeEnvironment, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_node: Optional[bool] = None, + image: str | None = None, + env_management_node: bool | None = None, ) -> None: """ Creates and writes a manifest.json file for a Node.js application. @@ -2586,13 +2582,13 @@ def write_quarto_manifest_json( file_or_directory: str, inspect: QuartoInspectResult, app_mode: AppMode, - environment: Optional[Environment], + environment: Environment | None, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, - env_management_py: Optional[bool] = None, - env_management_r: Optional[bool] = None, - r_environment: Optional[REnvironment] = None, + image: str | None = None, + env_management_py: bool | None = None, + env_management_r: bool | None = None, + r_environment: REnvironment | None = None, ) -> None: """ Creates and writes a manifest.json file for the given Quarto project. @@ -2635,7 +2631,7 @@ def write_tensorflow_manifest_json( directory: str, extra_files: Sequence[str], excludes: Sequence[str], - image: Optional[str] = None, + image: str | None = None, ) -> None: """ Creates and writes a manifest.json file for the given TensorFlow content. diff --git a/rsconnect/certificates.py b/rsconnect/certificates.py index a57be574f..be9f0e7e8 100644 --- a/rsconnect/certificates.py +++ b/rsconnect/certificates.py @@ -35,7 +35,7 @@ def read_certificate_file(location: str) -> str | bytes: return bFile.read() if suffix in TEXT_ENCODED_FILETYPES: - with open(path, "r") as tFile: + with open(path) as tFile: return tFile.read() except OSError as exc: raise RSConnectException("The certificate file %s could not be read: %s" % (location, exc)) from exc diff --git a/rsconnect/connect_cloud.py b/rsconnect/connect_cloud.py index ed44f2678..88ffc8ae5 100644 --- a/rsconnect/connect_cloud.py +++ b/rsconnect/connect_cloud.py @@ -9,7 +9,7 @@ from __future__ import annotations import os -from typing import Any, NamedTuple, Optional +from typing import Any, NamedTuple from urllib.parse import urlparse from packaging.specifiers import InvalidSpecifier, Specifier, SpecifierSet @@ -121,12 +121,12 @@ def environment_name() -> str: return name -def urls(environment: Optional[str] = None) -> ConnectCloudUrls: +def urls(environment: str | None = None) -> ConnectCloudUrls: """The URLs for the given (or currently selected) Connect Cloud environment.""" return _ENVIRONMENTS[environment or environment_name()] -def client_id(environment: Optional[str] = None) -> str: +def client_id(environment: str | None = None) -> str: """The OAuth client ID to authenticate this CLI with.""" override = os.environ.get(OAUTH_CLIENT_ID_ENV_VAR) if override: @@ -139,7 +139,7 @@ def client_id(environment: Optional[str] = None) -> str: SERVER_NAME = "connect.posit.cloud" -def _canonical_api_url(url: str) -> Optional[str]: +def _canonical_api_url(url: str) -> str | None: """The environment API base URL that `url` refers to, or None. Tolerates only scheme/host case and a trailing slash; the path, port, and @@ -155,7 +155,7 @@ def _canonical_api_url(url: str) -> Optional[str]: return None -def is_connect_cloud_url(url: Optional[str]) -> bool: +def is_connect_cloud_url(url: str | None) -> bool: """Whether a --server value or stored URL refers to Connect Cloud. Matches the pseudo-server name and the API base URL of every environment, @@ -171,7 +171,7 @@ def is_connect_cloud_url(url: Optional[str]) -> bool: return _canonical_api_url(url) is not None -def resolve_url(url: Optional[str]) -> str: +def resolve_url(url: str | None) -> str: """Turn a --server value into the API base URL for the selected environment. Recognized API URLs are canonicalized (case, trailing slash), so the stored @@ -182,7 +182,7 @@ def resolve_url(url: Optional[str]) -> str: return _canonical_api_url(url) or url -def environment_for_url(url: Optional[str]) -> str: +def environment_for_url(url: str | None) -> str: """Which environment an API base URL belongs to. A saved server records only its API URL, so this is how everything else about @@ -199,7 +199,7 @@ def environment_for_url(url: Optional[str]) -> str: return environment_name() -def login_interactive(environment: Optional[str] = None) -> dict[str, Any]: +def login_interactive(environment: str | None = None) -> dict[str, Any]: """Authenticate with the OAuth device code flow. Prints a verification URL and user code, then polls until the user @@ -219,7 +219,7 @@ def login_interactive(environment: Optional[str] = None) -> dict[str, Any]: def login_client_credentials( client_id_value: str, client_secret: str, - environment: Optional[str] = None, + environment: str | None = None, ) -> dict[str, Any]: """Authenticate with the OAuth client credentials grant, for CI. @@ -238,10 +238,10 @@ def login_client_credentials( def refresh( refresh_token: str, - environment: Optional[str] = None, - request_timeout: Optional[float] = None, - request_deadline: Optional[float] = None, - client_id_override: Optional[str] = None, + environment: str | None = None, + request_timeout: float | None = None, + request_deadline: float | None = None, + client_id_override: str | None = None, *, suppress_response_logging: bool = False, ) -> dict[str, Any]: @@ -279,9 +279,9 @@ def keyring_key(url: str, nickname: str) -> str: def store_credentials_in_keyring( url: str, nickname: str, - access_token: Optional[str], - refresh_token: Optional[str], - client_secret: Optional[str], + access_token: str | None, + refresh_token: str | None, + client_secret: str | None, ) -> bool: """Store a saved credential's secrets in the system keyring, replacing all of them. @@ -298,7 +298,7 @@ def store_credentials_in_keyring( ) -def store_tokens_in_keyring(url: str, nickname: str, access_token: Optional[str], refresh_token: Optional[str]) -> bool: +def store_tokens_in_keyring(url: str, nickname: str, access_token: str | None, refresh_token: str | None) -> bool: """Store (or, for empty values, delete) a saved credential's tokens. Leaves any stored client secret alone: a token refresh rotates the tokens @@ -310,7 +310,7 @@ def store_tokens_in_keyring(url: str, nickname: str, access_token: Optional[str] ) -def client_secret_from_keyring(url: str, nickname: str) -> tuple[bool, Optional[str]]: +def client_secret_from_keyring(url: str, nickname: str) -> tuple[bool, str | None]: """The stored client secret, and whether the keyring could be read. A read failure is not the same as no secret: overwriting one that may be there @@ -319,7 +319,7 @@ def client_secret_from_keyring(url: str, nickname: str) -> tuple[bool, Optional[ return keyring_read_value(keyring_key(url, nickname), CLIENT_SECRET_FIELD) -def credentials_from_keyring(url: str, nickname: str) -> tuple[Optional[str], Optional[str], Optional[str]]: +def credentials_from_keyring(url: str, nickname: str) -> tuple[str | None, str | None, str | None]: """A saved credential's secrets from the system keyring, as (access token, refresh token, client secret). Each is None when absent.""" key = keyring_key(url, nickname) @@ -351,7 +351,7 @@ def delete_credentials_from_keyring(url: str, nickname: str) -> None: _LOWER_BOUND_OPERATORS = (">=", ">", "==", "===", "~=") -def _clause_version(clause: Specifier) -> Optional[Version]: +def _clause_version(clause: Specifier) -> Version | None: """The version a single specifier clause names, or None if it cannot be parsed. Strips the wildcard from "==3.11.*", which is not a version on its own. @@ -362,7 +362,7 @@ def _clause_version(clause: Specifier) -> Optional[Version]: return None -def _effective_floor(specifier: SpecifierSet) -> Optional[Version]: +def _effective_floor(specifier: SpecifierSet) -> Version | None: """The lowest version the constraint admits, or None if it has no lower bound. Clauses are ANDed, so the highest of their floors is the one that binds: @@ -423,7 +423,7 @@ def _line_permits_some_patch(minor: str, specifier: SpecifierSet) -> bool: _LINE_SCAN_LIMIT = 20 -def _lowest_admitted_line(floor: Version, specifier: SpecifierSet) -> Optional[str]: +def _lowest_admitted_line(floor: Version, specifier: SpecifierSet) -> str | None: """The lowest MAJOR.MINOR at or above `floor` that the constraint admits. Usually the floor's own line. It is not when an exclusion empties that line, as @@ -441,7 +441,7 @@ def _lowest_admitted_line(floor: Version, specifier: SpecifierSet) -> Optional[s return None -def _minor_version(version: Version) -> Optional[str]: +def _minor_version(version: Version) -> str | None: """A version as the MAJOR.MINOR string Connect Cloud names its interpreters by. None when the version names no minor, as "==3.*" does: there is no single line @@ -452,7 +452,7 @@ def _minor_version(version: Version) -> Optional[str]: return "%d.%d" % (version.release[0], version.release[1]) -def _parsed(version: str) -> Optional[Version]: +def _parsed(version: str) -> Version | None: try: return Version(version) except InvalidVersion: @@ -471,7 +471,7 @@ def _log_requested(minor: str) -> str: return minor -def resolve_python_version(requires: Optional[str], local_version: Optional[str]) -> Optional[str]: +def resolve_python_version(requires: str | None, local_version: str | None) -> str | None: """Pick the Connect Cloud Python version for a deploy. `requires` is the PEP 440 constraint from the manifest's diff --git a/rsconnect/device_login.py b/rsconnect/device_login.py index b928d164f..2da454d40 100644 --- a/rsconnect/device_login.py +++ b/rsconnect/device_login.py @@ -13,7 +13,8 @@ import tempfile import time from contextlib import contextmanager -from typing import Any, Dict, Generator, Mapping, Optional, cast +from typing import Any, cast +from collections.abc import Generator, Mapping from urllib.parse import urlsplit, urlunsplit from . import api, connect_cloud @@ -151,7 +152,7 @@ def _validate_url_policy(parts: Any, label: str, allow_query: bool, allow_fragme raise RSConnectException("%s must not contain a query or fragment." % label) -def _format_authority(host: str, port: Optional[int], scheme: str) -> str: +def _format_authority(host: str, port: int | None, scheme: str) -> str: host = host.lower() authority = "[%s]" % host if ":" in host else host if port is not None and port != (443 if scheme == "https" else 80): @@ -168,7 +169,7 @@ def _normalize_server_url(url: str) -> str: return urlunsplit((parts.scheme.lower(), authority, path, "", "")) -def _cloud_server_url(url: Optional[str]) -> str: +def _cloud_server_url(url: str | None) -> str: if url is not None and not connect_cloud.is_connect_cloud_url(_identifier(url, "Connect Cloud URL")): raise RSConnectException("Connect Cloud URL must identify a supported environment.") return _normalize_server_url(connect_cloud.resolve_url(url)) @@ -290,7 +291,7 @@ def _open_state_file(path: str, flags: int, mode: int, purpose: str) -> int: def _open_state_lock(kind: str, name: str) -> int: path = _state_path(kind, name) + ".lock" directory = os.path.dirname(path) - descriptor: Optional[int] = None + descriptor: int | None = None try: os.makedirs(directory, mode=0o700, exist_ok=True) flags = os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) @@ -413,7 +414,7 @@ def _validate_state_identity(kind: str, name: str, raw: Any) -> dict[str, Any]: for key in _STATE_REQUIRED: if key not in raw: raise RSConnectException("Pending device login state is invalid.") - state = cast(Dict[str, Any], raw) + state = cast(dict[str, Any], raw) if type(state["version"]) is not int or state["version"] != 1 or state["kind"] != kind or state["name"] != name: raise RSConnectException("Pending device login state does not match the requested login.") _identifier(state["name"], "Nickname") @@ -481,7 +482,7 @@ def _validate_state(kind: str, name: str, raw: Any) -> dict[str, Any]: return state -def _read_state(kind: str, name: str) -> Optional[dict[str, Any]]: +def _read_state(kind: str, name: str) -> dict[str, Any] | None: path = _state_path(kind, name) flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) try: @@ -528,7 +529,7 @@ def _remove_state(state: dict[str, Any]) -> None: raise -def _ca_values(ca_data: Optional[str | bytes]) -> tuple[Optional[str], Optional[str]]: +def _ca_values(ca_data: str | bytes | None) -> tuple[str | None, str | None]: if ca_data is None: return None, None if isinstance(ca_data, str): @@ -538,7 +539,7 @@ def _ca_values(ca_data: Optional[str | bytes]) -> tuple[Optional[str], Optional[ raise RSConnectException("CA data must be text or bytes.") -def _state_ca(state: dict[str, Any]) -> Optional[str | bytes]: +def _state_ca(state: dict[str, Any]) -> str | bytes | None: if state["ca_data_b64"] is not None: return base64.b64decode(state["ca_data_b64"].encode("ascii"), validate=True) return state["ca_data"] @@ -553,9 +554,7 @@ def _same_server(value: Any, server: str) -> bool: return False -def _assert_nickname_target( - store: ServerStore, kind: str, name: str, server: str, account: Optional[str] = None -) -> None: +def _assert_nickname_target(store: ServerStore, kind: str, name: str, server: str, account: str | None = None) -> None: entry = store.get_by_name(name) if entry is None: return @@ -574,7 +573,7 @@ def _saved_server_kind(entry: Mapping[str, Any]) -> str: return "connect" -def _saved_connect_entry(store: ServerStore, name: str, server: str) -> Optional[ServerDataDict]: +def _saved_connect_entry(store: ServerStore, name: str, server: str) -> ServerDataDict | None: named = store.get_by_name(name) if named is not None: return named @@ -585,8 +584,8 @@ def _saved_connect_entry(store: ServerStore, name: str, server: str) -> Optional def _resolve_tls( - saved: Optional[ServerDataDict], insecure: bool, ca_data: Optional[str | bytes], client_id: Optional[str] -) -> tuple[bool, Optional[str | bytes], Optional[str]]: + saved: ServerDataDict | None, insecure: bool, ca_data: str | bytes | None, client_id: str | None +) -> tuple[bool, str | bytes | None, str | None]: tls_insecure, tls_ca = _tls_settings(saved, insecure, ca_data) saved_id = saved.get("oauth_client_id") if saved else None resolved_client_id = client_id if client_id is not None else (str(saved_id) if saved_id else None) @@ -596,8 +595,8 @@ def _resolve_tls( def _tls_settings( - saved: Optional[ServerDataDict], insecure: bool, ca_data: Optional[str | bytes] -) -> tuple[bool, Optional[str | bytes]]: + saved: ServerDataDict | None, insecure: bool, ca_data: str | bytes | None +) -> tuple[bool, str | bytes | None]: if insecure and ca_data is not None: raise RSConnectException("Cannot combine insecure TLS with a custom CA certificate.") if insecure or ca_data is not None: @@ -615,10 +614,10 @@ def _check_pending_target( state: dict[str, Any], kind: str, server: str, - account: Optional[str], - client_id: Optional[str], + account: str | None, + client_id: str | None, insecure: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, ) -> None: matches = state["server"] == server if kind == "cloud": @@ -642,9 +641,9 @@ def _post_form( endpoint: str, fields: dict[str, str], insecure: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, request_timeout: float, - request_deadline: Optional[float] = None, + request_deadline: float | None = None, ) -> Any: base, path = _endpoint_location(endpoint) return _post_oauth_form_request( @@ -672,7 +671,7 @@ def _register_device_client( metadata: dict[str, Any], server: str, insecure: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, deadline: float, ) -> str: request_timeout = _remaining(deadline) @@ -697,9 +696,9 @@ def _start_device_request( metadata: dict[str, Any], server: str, client_id: str, - scope: Optional[str], + scope: str | None, insecure: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, deadline: float, ) -> tuple[str, dict[str, Any]]: client_id = _identifier(client_id, "OAuth client ID") @@ -739,11 +738,11 @@ def _make_state( metadata: dict[str, Any], response: dict[str, Any], client_id: str, - scope: Optional[str], + scope: str | None, set_default: bool, insecure: bool, - ca_data: Optional[str | bytes], - account: Optional[str], + ca_data: str | bytes | None, + account: str | None, ) -> dict[str, Any]: client_id = _identifier(client_id, "OAuth client ID") device_code = response.get("device_code") @@ -802,9 +801,9 @@ def start_connect_login( url: str, name: str, insecure: bool = False, - ca_data: Optional[str | bytes] = None, + ca_data: str | bytes | None = None, set_default: bool = True, - client_id: Optional[str] = None, + client_id: str | None = None, ) -> dict[str, Any]: require_posix("Resumable device login") name = _identifier(name, "Nickname") @@ -819,9 +818,9 @@ def _start_connect_login( url: str, name: str, insecure: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, set_default: bool, - client_id: Optional[str], + client_id: str | None, ) -> dict[str, Any]: server = _normalize_server_url(url) store = _store() @@ -863,7 +862,7 @@ def _start_connect_login( def start_cloud_login( account: str, name: str, - url: Optional[str] = None, + url: str | None = None, set_default: bool = False, ) -> dict[str, Any]: require_posix("Resumable device login") @@ -876,7 +875,7 @@ def start_cloud_login( def _start_cloud_login( account: str, name: str, - url: Optional[str], + url: str | None, set_default: bool, ) -> dict[str, Any]: account = _identifier(account, "Connect Cloud account") @@ -923,7 +922,7 @@ def _raise_device_error(code: Any) -> None: raise error_type() -def _response_data(response: Any) -> tuple[dict[str, Any], Optional[int]]: +def _response_data(response: Any) -> tuple[dict[str, Any], int | None]: data, status = _oauth_response_data(response) if data is None: raise RSConnectException("Device token request returned an unexpected response.") @@ -938,7 +937,7 @@ def _device_token_response(response: Any) -> dict[str, Any]: return data -def _validate_token_success(data: dict[str, Any], status: Optional[int]) -> None: +def _validate_token_success(data: dict[str, Any], status: int | None) -> None: if status is None or status < 200 or status >= 300: if status is None: raise RSConnectException("OAuth device token request failed.") @@ -948,7 +947,7 @@ def _validate_token_success(data: dict[str, Any], status: Optional[int]) -> None raise RSConnectException("Device token request returned no access token.") -def _poll_timeout(state: dict[str, Any], deadline: float) -> Optional[float]: +def _poll_timeout(state: dict[str, Any], deadline: float) -> float | None: remaining = deadline - time.monotonic() device_remaining = state["expires_at"] - time.time() if device_remaining <= 0: @@ -974,7 +973,7 @@ def _record_poll_error(state: dict[str, Any], error: Exception) -> None: _write_state(state) -def _poll_for_token(state: dict[str, Any], deadline: float) -> Optional[dict[str, Any]]: +def _poll_for_token(state: dict[str, Any], deadline: float) -> dict[str, Any] | None: while True: request_timeout = _poll_timeout(state, deadline) if request_timeout is None: @@ -1042,7 +1041,7 @@ def _checkpoint_key(state: dict[str, Any]) -> str: return "device-login:" + digest -def _read_keyring_checkpoint(state: dict[str, Any]) -> Optional[dict[str, Any]]: +def _read_keyring_checkpoint(state: dict[str, Any]) -> dict[str, Any] | None: readable, value = keyring_read_value(_checkpoint_key(state), "tokens") if not readable: raise RSConnectException("Could not read pending login tokens from the keyring. Unlock it and retry.") @@ -1055,7 +1054,7 @@ def _read_keyring_checkpoint(state: dict[str, Any]) -> Optional[dict[str, Any]]: _validate_tokens(tokens) if tokens is None: raise RSConnectException("Pending login tokens in the keyring are invalid.") - return cast(Dict[str, Any], tokens) + return cast(dict[str, Any], tokens) def _approved_tokens(state: dict[str, Any]) -> dict[str, Any]: @@ -1204,7 +1203,7 @@ def _finalize_cloud(state: dict[str, Any], deadline: float) -> dict[str, Any]: def _invalid_grant_error(error: BaseException) -> bool: - current: Optional[BaseException] = error + current: BaseException | None = error while current is not None: if isinstance(current, InvalidGrantError): return True diff --git a/rsconnect/environment.py b/rsconnect/environment.py index de949c2b7..05081e42a 100644 --- a/rsconnect/environment.py +++ b/rsconnect/environment.py @@ -44,18 +44,18 @@ class Environment: def __init__( self, data: EnvironmentData, - python_interpreter: typing.Optional[str] = None, - python_version_requirement: typing.Optional[str] = None, + python_interpreter: str | None = None, + python_version_requirement: str | None = None, ): self._data = data # Fields that are not loaded from the environment subprocess self.python_version_requirement = python_version_requirement self.python_interpreter = python_interpreter - self.uv: typing.Optional[str] = None + self.uv: str | None = None # Optional override of server install behavior. If None, server-driven # default is used. - self.package_manager_allow_uv: typing.Optional[bool] = None + self.package_manager_allow_uv: bool | None = None def __getattr__(self, name: str) -> typing.Any: # We directly proxy the attributes of the EnvironmentData object @@ -91,9 +91,9 @@ def __repr__(self) -> str: @classmethod def from_dict( cls, - data: typing.Dict[str, typing.Any], - python_interpreter: typing.Optional[str] = None, - python_version_requirement: typing.Optional[str] = None, + data: dict[str, typing.Any], + python_interpreter: str | None = None, + python_version_requirement: str | None = None, ) -> "Environment": """Create an Environment instance from the dictionary representation of EnvironmentData.""" return cls( @@ -106,10 +106,10 @@ def from_dict( def create_python_environment( cls, directory: str, - requirements_file: typing.Optional[str] = "requirements.txt", - python: typing.Optional[str] = None, - override_python_version: typing.Optional[str] = None, - package_manager: typing.Optional[PackageInstaller] = None, + requirements_file: str | None = "requirements.txt", + python: str | None = None, + override_python_version: str | None = None, + package_manager: PackageInstaller | None = None, ) -> "Environment": """Given a project directory and a Python executable, return Environment information. @@ -190,9 +190,9 @@ def create_python_environment( def _get_python_env_info( cls, file_name: str, - python: typing.Optional[str], - requirements_file: typing.Optional[str] = "requirements.txt", - project_directory: typing.Optional[str] = None, + python: str | None, + requirements_file: str | None = "requirements.txt", + project_directory: str | None = None, ) -> "Environment": """ Gathers the python and environment information relating to the specified file @@ -217,7 +217,7 @@ def _inspect_environment( cls, python: str, directory: str, - requirements_file: typing.Optional[str] = "requirements.txt", + requirements_file: str | None = "requirements.txt", check_output: typing.Callable[..., bytes] = subprocess.check_output, ) -> "Environment": """Run the environment inspector against the specified python binary. @@ -274,7 +274,7 @@ def _uv_bin() -> str: return "uv" -def which_python(python: typing.Optional[str] = None, directory: typing.Optional[str] = None) -> str: +def which_python(python: str | None = None, directory: str | None = None) -> str: """Determines which Python executable to use. Explicit paths take precedence over active and project environments. @@ -288,7 +288,7 @@ def which_python(python: typing.Optional[str] = None, directory: typing.Optional raise RSConnectException(f"The path '{python}' is not executable. Expected a Python executable") return python - def interpreter(environment: typing.Union[str, pathlib.Path], conda: bool = False) -> typing.Optional[str]: + def interpreter(environment: str | pathlib.Path, conda: bool = False) -> str | None: executable = ( "python.exe" if os.name == "nt" and conda else "Scripts/python.exe" if os.name == "nt" else "bin/python" ) @@ -348,7 +348,7 @@ def fake_module_file_from_directory(directory: str) -> str: return os.path.join(directory, app_name + ".py") -def is_environment_dir(directory: typing.Union[str, pathlib.Path]) -> bool: +def is_environment_dir(directory: str | pathlib.Path) -> bool: """Detect whether `directory` is a virtualenv""" # A virtualenv will have Python at ./bin/python @@ -358,9 +358,9 @@ def is_environment_dir(directory: typing.Union[str, pathlib.Path]) -> bool: return os.path.exists(python_path) or os.path.exists(win_path) -def list_environment_dirs(directory: typing.Union[str, pathlib.Path]) -> typing.List[str]: +def list_environment_dirs(directory: str | pathlib.Path) -> list[str]: """Returns a list of subdirectories in `directory` that appear to contain virtual environments.""" - envs: typing.List[str] = [] + envs: list[str] = [] for name in os.listdir(directory): path = os.path.join(directory, name) @@ -380,7 +380,7 @@ def _warn_on_ignored_manifest(directory: str) -> None: warn_user(" Warning: the existing manifest.json file will not be used or considered.") -def _check_requirements_file(directory: str, requirements_file: typing.Optional[str]) -> typing.Optional[str]: +def _check_requirements_file(directory: str, requirements_file: str | None) -> str | None: """ Verify that a requirements file exists inside the deployment directory. @@ -409,7 +409,7 @@ def _check_requirements_file(directory: str, requirements_file: typing.Optional[ return str(relative_path) -def _warn_if_environment_directory(directory: typing.Union[str, pathlib.Path]) -> None: +def _warn_if_environment_directory(directory: str | pathlib.Path) -> None: """ Issue a warning if the deployment directory is itself a virtualenv (yikes!). @@ -434,7 +434,7 @@ def _warn_on_ignored_requirements(directory: str, requirements_file_name: str) - warn_user(" Warning: the existing %s file will not be used or considered." % requirements_file_name) -def _warn_on_missing_python_version(version_constraint: typing.Optional[str]) -> None: +def _warn_on_missing_python_version(version_constraint: str | None) -> None: """ Check that the project has a Python version constraint requested. If it doesn't warn the user that it should be specified. diff --git a/rsconnect/environment_node.py b/rsconnect/environment_node.py index 55a2b5858..ab4d0c329 100644 --- a/rsconnect/environment_node.py +++ b/rsconnect/environment_node.py @@ -11,7 +11,6 @@ import locale import os import subprocess -from typing import Optional from .exception import RSConnectException from .log import logger @@ -44,7 +43,7 @@ def __init__( def create( cls, directory: str, - node_executable: Optional[str] = None, + node_executable: str | None = None, ) -> NodeEnvironment: """Detect Node.js environment from a project directory. diff --git a/rsconnect/environment_r.py b/rsconnect/environment_r.py index 684bec8d0..435a226fa 100644 --- a/rsconnect/environment_r.py +++ b/rsconnect/environment_r.py @@ -11,7 +11,8 @@ import json import os -from typing import Any, Optional, Sequence, cast +from typing import Any, cast +from collections.abc import Sequence from .exception import RSConnectException from .log import logger @@ -43,7 +44,7 @@ def __init__( self.lockfile = DEFAULT_R_PACKAGE_FILE @classmethod - def create(cls, directory: str) -> Optional["REnvironment"]: + def create(cls, directory: str) -> REnvironment | None: """Resolve R dependencies from an renv.lock file in a project directory. Returns None when there is no renv.lock to resolve, so callers can treat @@ -178,7 +179,7 @@ def _resolve_package_source(pkg: Any, repo_name_to_url: dict[str, str]) -> tuple return pkg.get("Source") or "", pkg.get("Repository") or "" -def _resolve_repo_and_source(repo_name_to_url: dict[str, str], repo_str: str, src: Optional[str]) -> tuple[str, str]: +def _resolve_repo_and_source(repo_name_to_url: dict[str, str], repo_str: str, src: str | None) -> tuple[str, str]: if _is_url(repo_str): repo_url = repo_str.rstrip("/") repo_name = repo_url @@ -291,7 +292,7 @@ def _remote_repo_url(remote_type: str, pkg_ref: str) -> str: return f"{host}{pkg_ref}" if host else "" -def _join_list(value: Optional[Sequence[Optional[str]]]) -> Optional[str]: +def _join_list(value: Sequence[str | None] | None) -> str | None: items = [v for v in value if v is not None] if value else [] return ", ".join(items) if items else None diff --git a/rsconnect/exception.py b/rsconnect/exception.py index 544dac193..ce434feb9 100644 --- a/rsconnect/exception.py +++ b/rsconnect/exception.py @@ -1,11 +1,9 @@ from __future__ import annotations -from typing import Optional - class RSConnectException(Exception): - def __init__(self, message: str, cause: Optional[Exception] = None, status: Optional[int] = None): - super(RSConnectException, self).__init__(message) + def __init__(self, message: str, cause: Exception | None = None, status: int | None = None): + super().__init__(message) self.message = message self.cause = cause self.status = status diff --git a/rsconnect/git_metadata.py b/rsconnect/git_metadata.py index a0c315724..e239980e7 100644 --- a/rsconnect/git_metadata.py +++ b/rsconnect/git_metadata.py @@ -5,13 +5,12 @@ from __future__ import annotations import subprocess -from typing import Optional from urllib.parse import urlparse from .log import logger -def _run_git_command(args: list[str], cwd: str) -> Optional[str]: +def _run_git_command(args: list[str], cwd: str) -> str | None: """ Run a git command and return its output. @@ -59,7 +58,7 @@ def has_uncommitted_changes(directory: str) -> bool: return bool(result) -def get_git_commit(directory: str) -> Optional[str]: +def get_git_commit(directory: str) -> str | None: """ Get the current git commit SHA. @@ -69,7 +68,7 @@ def get_git_commit(directory: str) -> Optional[str]: return _run_git_command(["rev-parse", "HEAD"], directory) -def get_git_branch(directory: str) -> Optional[str]: +def get_git_branch(directory: str) -> str | None: """ Get the current git branch name or tag. @@ -88,7 +87,7 @@ def get_git_branch(directory: str) -> Optional[str]: return branch -def get_git_remote_url(directory: str, remote: str = "origin") -> Optional[str]: +def get_git_remote_url(directory: str, remote: str = "origin") -> str | None: """ Get the URL of a git remote. @@ -99,7 +98,7 @@ def get_git_remote_url(directory: str, remote: str = "origin") -> Optional[str]: return _run_git_command(["remote", "get-url", remote], directory) -def normalize_git_url_to_https(url: Optional[str]) -> Optional[str]: +def normalize_git_url_to_https(url: str | None) -> str | None: """ Normalize a git URL to HTTPS format. diff --git a/rsconnect/http_support.py b/rsconnect/http_support.py index 92f79444c..671716b96 100644 --- a/rsconnect/http_support.py +++ b/rsconnect/http_support.py @@ -14,7 +14,8 @@ import time from http import client as http from http.cookies import SimpleCookie -from typing import IO, Any, Dict, List, Mapping, Optional, Tuple, Union, cast +from typing import IO, Any, Union, cast +from collections.abc import Mapping from urllib.parse import unquote_plus, urlencode, urljoin, urlparse from warnings import warn @@ -23,15 +24,15 @@ from .timeouts import get_request_timeout # A union type that describes types that can be converted to and from JSON. -JsonData = Union[ +JsonData = Union[ # noqa: UP007 str, int, float, bool, None, - List["JsonData"], - Tuple["JsonData"], - Dict[str, "JsonData"], + list["JsonData"], + tuple["JsonData"], + dict[str, "JsonData"], ] _user_agent = f"RSConnectPython/{VERSION}" @@ -167,9 +168,9 @@ def _redacted_body_for_log(body: object) -> object: # noinspection PyUnusedLocal,PyUnresolvedReferences def _create_plain_connection( host_name: str, - port: Optional[int], + port: int | None, disable_tls_check: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, ): """ This function is used to create a plain HTTP connection. Note that the 3rd and 4th @@ -215,9 +216,9 @@ def _get_proxy_headers(*args: object, **kwargs: object): # noinspection PyUnresolvedReferences def _create_ssl_connection( host_name: str, - port: Optional[int], + port: int | None, disable_tls_check: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, ): """ This function is used to create a TLS encrypted HTTP connection (SSL). @@ -292,9 +293,9 @@ def append_to_path(uri: str, path: str): def create_multipart_form_data( - fields: Dict[str, Union[str, Tuple[str, bytes, str]]], - boundary: Optional[str] = None, -) -> Tuple[bytes, str]: + fields: dict[str, str | tuple[str, bytes, str]], + boundary: str | None = None, +) -> tuple[bytes, str]: """ Create multipart/form-data body and content-type header. @@ -312,14 +313,14 @@ def create_multipart_form_data( body_parts = [] for field_name, field_value in fields.items(): - body_parts.append(f"--{boundary}".encode("utf-8")) + body_parts.append(f"--{boundary}".encode()) if isinstance(field_value, tuple): # File field filename, file_content, content_type = field_value disposition = f'Content-Disposition: form-data; name="{field_name}"; filename="{filename}"' body_parts.append(disposition.encode("utf-8")) - body_parts.append(f"Content-Type: {content_type}".encode("utf-8")) + body_parts.append(f"Content-Type: {content_type}".encode()) body_parts.append(b"") body_parts.append(file_content) else: @@ -329,7 +330,7 @@ def create_multipart_form_data( body_parts.append(b"") body_parts.append(field_value.encode("utf-8")) - body_parts.append(f"--{boundary}--".encode("utf-8")) + body_parts.append(f"--{boundary}--".encode()) body_parts.append(b"") body = b"\r\n".join(body_parts) @@ -338,7 +339,7 @@ def create_multipart_form_data( return body, content_type -def _interrupt_socket(sock: Optional[socket.socket]) -> None: +def _interrupt_socket(sock: socket.socket | None) -> None: if sock is not None: try: sock.shutdown(socket.SHUT_RDWR) @@ -347,7 +348,7 @@ def _interrupt_socket(sock: Optional[socket.socket]) -> None: def _close_failed_request( - connection: Union[http.HTTPConnection, http.HTTPSConnection], response: Optional[http.HTTPResponse] + connection: http.HTTPConnection | http.HTTPSConnection, response: http.HTTPResponse | None ) -> None: if response is not None: try: @@ -360,7 +361,7 @@ def _close_failed_request( pass -class HTTPResponse(object): +class HTTPResponse: """ This class represents the result of executing an HTTP request. """ @@ -368,9 +369,9 @@ class HTTPResponse(object): def __init__( self, full_uri: str, - response: Optional[http.HTTPResponse] = None, - body: Optional[str | bytes] = None, - exception: Optional[Exception] = None, + response: http.HTTPResponse | None = None, + body: str | bytes | None = None, + exception: Exception | None = None, ): """ This constructs an HTTPResponse object. One and only one of the arguments will @@ -409,7 +410,7 @@ def __init__( except json.decoder.JSONDecodeError: self.response_body - def getheader(self, name: str) -> Optional[str]: + def getheader(self, name: str) -> str | None: """ This method retrieves a specific header from the response. @@ -421,7 +422,7 @@ def getheader(self, name: str) -> Optional[str]: return self._response.getheader(name) -class HTTPServer(object): +class HTTPServer: """ This class provides the means to simply and directly invoke HTTP requests against a server. @@ -431,10 +432,10 @@ def __init__( self, url: str, disable_tls_check: bool = False, - ca_data: Optional[str | bytes] = None, - cookies: Optional[CookieJar] = None, - request_timeout: Optional[float] = None, - request_deadline: Optional[float] = None, + ca_data: str | bytes | None = None, + cookies: CookieJar | None = None, + request_timeout: float | None = None, + request_deadline: float | None = None, ): """ Constructs an HTTPServer object. @@ -512,7 +513,7 @@ def __exit__(self, *args: object): def get( self, path: str, - query_params: Optional[Mapping[str, JsonData]] = None, + query_params: Mapping[str, JsonData] | None = None, decode_response: bool = True, ) -> JsonData | HTTPResponse: return self.request("GET", path, query_params, decode_response=decode_response) @@ -520,9 +521,9 @@ def get( def post( self, path: str, - query_params: Optional[Mapping[str, JsonData]] = None, + query_params: Mapping[str, JsonData] | None = None, body: str | bytes | IO[bytes] | Mapping[str, Any] | list[Any] | None = None, - headers: Optional[Mapping[str, str]] = None, + headers: Mapping[str, str] | None = None, ) -> JsonData | HTTPResponse: if headers is None: headers = {} @@ -531,7 +532,7 @@ def post( def patch( self, path: str, - query_params: Optional[Mapping[str, JsonData]] = None, + query_params: Mapping[str, JsonData] | None = None, body: str | bytes | IO[bytes] | Mapping[str, Any] | list[Any] | None = None, ) -> JsonData | HTTPResponse: return self.request("PATCH", path, query_params, body) @@ -539,9 +540,9 @@ def patch( def put( self, path: str, - query_params: Optional[Mapping[str, JsonData]] = None, + query_params: Mapping[str, JsonData] | None = None, body: str | bytes | IO[bytes] | Mapping[str, Any] | list[Any] | None = None, - headers: Optional[Mapping[str, str]] = None, + headers: Mapping[str, str] | None = None, decode_response: bool = True, ) -> JsonData | HTTPResponse: if headers is None: @@ -553,7 +554,7 @@ def put( def delete( self, path: str, - query_params: Optional[Mapping[str, JsonData]] = None, + query_params: Mapping[str, JsonData] | None = None, body: str | bytes | IO[bytes] | Mapping[str, Any] | list[Any] | None = None, decode_response: bool = True, ) -> JsonData | HTTPResponse: @@ -563,11 +564,11 @@ def request( self, method: str, path: str, - query_params: Optional[Mapping[str, JsonData]] = None, + query_params: Mapping[str, JsonData] | None = None, body: str | bytes | IO[bytes] | Mapping[str, Any] | list[Any] | None = None, maximum_redirects: int = 5, decode_response: bool = True, - headers: Optional[Mapping[str, str]] = None, + headers: Mapping[str, str] | None = None, ) -> JsonData | HTTPResponse: path = self._get_full_path(path) extra_headers = headers or {} @@ -585,7 +586,7 @@ def _apply_request_deadline(self) -> None: return remaining = self.request_deadline - time.monotonic() if remaining <= 0: - raise socket.timeout("HTTP request deadline exceeded.") + raise TimeoutError("HTTP request deadline exceeded.") timeout = self.request_timeout if self.request_timeout is not None else get_request_timeout() self.request_timeout = min(timeout, remaining) if timeout else remaining if self._conn is not None: @@ -595,12 +596,12 @@ def _apply_request_deadline(self) -> None: def _request_with_deadline( self, - connection: Union[http.HTTPConnection, http.HTTPSConnection], + connection: http.HTTPConnection | http.HTTPSConnection, method: str, full_uri: str, body: str | bytes | IO[bytes] | None, headers: dict[str, str], - ) -> Tuple[http.HTTPResponse, bytes]: + ) -> tuple[http.HTTPResponse, bytes]: deadline = self.request_deadline if deadline is None: connection.request(method, full_uri, body, headers) @@ -610,7 +611,7 @@ def _request_with_deadline( self._apply_request_deadline() remaining = deadline - time.monotonic() if remaining <= 0: - raise socket.timeout("HTTP request deadline exceeded.") + raise TimeoutError("HTTP request deadline exceeded.") # ponytail: shutdown cannot cancel OS DNS or blocked source reads; revisit if either must fit this deadline. request_socket = connection.sock @@ -625,17 +626,17 @@ def interrupt_request() -> None: timer = threading.Timer(remaining, interrupt_request) timer.daemon = True timer.start() - response: Optional[http.HTTPResponse] = None + response: http.HTTPResponse | None = None try: connection.request(method, full_uri, body, headers) with request_lock: request_socket = connection.sock or request_socket if time.monotonic() >= deadline: - raise socket.timeout("HTTP request deadline exceeded.") + raise TimeoutError("HTTP request deadline exceeded.") response = connection.getresponse() with request_lock: if time.monotonic() >= deadline: - raise socket.timeout("HTTP request deadline exceeded.") + raise TimeoutError("HTTP request deadline exceeded.") response_body = response.read() with request_lock: # A complete token response must reach its checkpoint even after the deadline. @@ -643,7 +644,7 @@ def interrupt_request() -> None: return response, response_body except Exception: if time.monotonic() >= deadline: - raise socket.timeout("HTTP request deadline exceeded.") from None + raise TimeoutError("HTTP request deadline exceeded.") from None raise finally: timer.cancel() @@ -693,7 +694,7 @@ def _do_request( self, method: str, path: str, - query_params: Optional[Mapping[str, JsonData]], + query_params: Mapping[str, JsonData] | None, body: str | bytes | IO[bytes] | None, maximum_redirects: int, extra_headers: dict[str, str], @@ -721,7 +722,7 @@ def _do_request( local_connection = True # At this point we know that self._conn is not None. - conn = cast(Union[http.HTTPConnection, http.HTTPSConnection], self._conn) + conn = cast(http.HTTPConnection | http.HTTPSConnection, self._conn) try: response, response_body = self._request_with_deadline(conn, method, full_uri, body, headers) @@ -747,14 +748,12 @@ def _do_request( return self._tweak_response(HTTPResponse(full_uri, response=response, body=response_body)) except ( + TimeoutError, http.HTTPException, ssl.CertificateError, - IOError, OSError, - socket.error, socket.herror, socket.gaierror, - socket.timeout, ) as exception: logger.debug("An exception occurred processing the HTTP request (%s)." % type(exception).__name__) return HTTPResponse(full_uri, exception=exception) @@ -762,7 +761,7 @@ def _do_request( def _follow_redirect( self, response: http.HTTPResponse, - query_params: Optional[Mapping[str, JsonData]], + query_params: Mapping[str, JsonData] | None, body: str | bytes | IO[bytes] | None, maximum_redirects: int, extra_headers: dict[str, str], @@ -846,11 +845,11 @@ def request( self, method: str, path: str, - query_params: Optional[Mapping[str, JsonData]] = None, + query_params: Mapping[str, JsonData] | None = None, body: str | bytes | IO[bytes] | Mapping[str, Any] | list[Any] | None = None, maximum_redirects: int = 5, decode_response: bool = True, - headers: Optional[Mapping[str, str]] = None, + headers: Mapping[str, str] | None = None, ) -> JsonData | HTTPResponse: if not self._can_refresh_token(): return super().request(method, path, query_params, body, maximum_redirects, decode_response, headers) # pyright: ignore[reportUnknownArgumentType] @@ -873,7 +872,7 @@ def request( return response -class CookieJar(object): +class CookieJar: @staticmethod def from_dict(source: dict[str, Any]): if not isinstance(source, dict): diff --git a/rsconnect/json_web_token.py b/rsconnect/json_web_token.py index 6b9e3bdc8..cb4cb9541 100644 --- a/rsconnect/json_web_token.py +++ b/rsconnect/json_web_token.py @@ -7,8 +7,8 @@ import base64 import binascii import os -from datetime import datetime, timedelta, timezone -from typing import Any, Optional +from datetime import datetime, timedelta, UTC +from typing import Any import jwt @@ -25,7 +25,7 @@ SECRET_KEY_ENV = "CONNECT_BOOTSTRAP_SECRETKEY" -def read_secret_key(keypath: Optional[str]) -> bytes: +def read_secret_key(keypath: str | None) -> bytes: """ Reads a secret key as bytes given a path to a file containing a base64-encoded key. @@ -53,7 +53,7 @@ def read_secret_key(keypath: Optional[str]) -> bytes: if not os.path.exists(keypath): raise RSConnectException("Keypath does not exist.") - with open(keypath, "r") as f: + with open(keypath) as f: raw_data = f.read() if raw_data is None: raise RSConnectException("Secret key cannot be 'None'") @@ -153,7 +153,7 @@ def generate_standard_claims(self, current_datetime: datetime, exp: timedelta): def new_token(self, custom_claims: dict[str, Any], exp: timedelta) -> str: - standard_claims = self.generate_standard_claims(datetime.now(tz=timezone.utc), exp) + standard_claims = self.generate_standard_claims(datetime.now(tz=UTC), exp) claims: dict[str, Any] = {} for c in [standard_claims, custom_claims]: diff --git a/rsconnect/log.py b/rsconnect/log.py index c0884c500..2efe7b6bc 100644 --- a/rsconnect/log.py +++ b/rsconnect/log.py @@ -8,7 +8,8 @@ import logging import sys from functools import partial, wraps -from typing import TYPE_CHECKING, Any, Callable, Concatenate, Literal, Optional, ParamSpec, Protocol, TypeVar +from typing import TYPE_CHECKING, Any, Concatenate, Literal, ParamSpec, Protocol, TypeVar +from collections.abc import Callable if TYPE_CHECKING: from collections.abc import MutableMapping @@ -25,7 +26,7 @@ logging.addLevelName(VERBOSE, "VERBOSE") -class LogOutputFormat(object): +class LogOutputFormat: TEXT = "text" JSON = "json" DEFAULT = TEXT @@ -42,7 +43,7 @@ class JsonLogFormatter(logging.Formatter): @param str datefmt: Key: strftime format string """ - def __init__(self, fmt_dict: Optional[dict[str, str]] = None, datefmt: str = _DATE_FORMAT): + def __init__(self, fmt_dict: dict[str, str] | None = None, datefmt: str = _DATE_FORMAT): self.fmt_dict = ( fmt_dict if fmt_dict is not None else {"timestamp": "asctime", "level": "levelname", "message": "message"} ) @@ -93,7 +94,7 @@ def format(self, record: logging.LogRecord): class RSLogger(_LoggerAdapter): def __init__(self): - super(RSLogger, self).__init__(logging.getLogger("rsconnect"), {}) + super().__init__(logging.getLogger("rsconnect"), {}) self._in_feedback = False self._have_feedback_output = False self._log_format = LogOutputFormat.DEFAULT @@ -123,7 +124,7 @@ def set_log_output_format(self, value: LogOutputFormat.All): h.setFormatter(logging.Formatter("[%(levelname)s] %(asctime)s %(message)s", datefmt=_DATE_FORMAT)) def process(self, msg: str, kwargs: MutableMapping[str, Any]): - msg, kwargs = super(RSLogger, self).process(msg, kwargs) + msg, kwargs = super().process(msg, kwargs) if self._in_feedback and self.is_debugging(): if not self._have_feedback_output: print() @@ -199,7 +200,7 @@ def wrapper(*args: P.args, **kw: P.kwargs): try: result = f(*args, **kw) except Exception as exc: - logger.error(" \t[ERROR]: {}\n".format(str(exc))) + logger.error(f" \t[ERROR]: {str(exc)}\n") raise logger.debug(" \t[OK]\n") return result diff --git a/rsconnect/main.py b/rsconnect/main.py index a46fd63f2..3b5c1d5c4 100644 --- a/rsconnect/main.py +++ b/rsconnect/main.py @@ -16,16 +16,13 @@ from pathlib import Path from typing import ( Any, - Callable, - ItemsView, Literal, Never, - Optional, ParamSpec, - Sequence, TypeVar, cast, ) +from collections.abc import Callable, ItemsView, Sequence import click @@ -284,7 +281,7 @@ def wrapper(*args: P.args, **kwargs: P.kwargs): return wrapper -def _resolve_guid_option(new: Optional[bool], app_id: Optional[str], guid: Optional[str]) -> Optional[str]: +def _resolve_guid_option(new: bool | None, app_id: str | None, guid: str | None) -> str | None: """Fold --guid into the app_id that the deploy plumbing understands.""" if guid is None: return app_id @@ -363,8 +360,8 @@ def _start_connect_device_login(params: dict[str, Any]) -> dict[str, Any]: if params.get("identity_token") or params.get("identity_token_file"): raise RSConnectException("--no-wait cannot be combined with identity token authentication.") ctx = click.get_current_context() - server: Optional[str] = params.get("server") - positional: Optional[str] = params.get("server_arg") + server: str | None = params.get("server") + positional: str | None = params.get("server_arg") if positional and validation.get_parameter_source_name_from_ctx("server", ctx) == "COMMANDLINE": raise RSConnectException("You must specify only one of SERVER or -s/--server.") server = positional or server @@ -390,7 +387,7 @@ def _start_cloud_device_login(params: dict[str, Any]) -> dict[str, Any]: account = validation.effective_connect_cloud_account(ctx, params.get("account")) if not account: raise RSConnectException("--no-wait requires --account for Posit Connect Cloud.") - server: Optional[str] = params.get("server") + server: str | None = params.get("server") validation.validate_connection_options( ctx=ctx, url=server, @@ -591,7 +588,7 @@ def validate_env_vars(ctx: click.Context, param: click.Parameter, all_values: tu for s in all_values: if not isinstance(s, str): - raise click.BadParameter("environment variable must be a string: '{}'".format(s)) + raise click.BadParameter(f"environment variable must be a string: '{s}'") if "=" in s: name, value = s.split("=", 1) @@ -600,18 +597,18 @@ def validate_env_vars(ctx: click.Context, param: click.Parameter, all_values: tu # inherited value from the environment value = os.environ.get(s) if value is None: - raise click.BadParameter("'{}' not found in the environment".format(s)) + raise click.BadParameter(f"'{s}' not found in the environment") vars[s] = value return vars def prepare_deploy_metadata( - directory: Optional[str], + directory: str | None, metadata_overrides: tuple[str, ...], no_metadata: bool, - server_version: Optional[str] = None, -) -> Optional[dict[str, str]]: + server_version: str | None = None, +) -> dict[str, str] | None: """ Prepare metadata for bundle upload. @@ -765,9 +762,9 @@ def publish_args(func: Callable[P, T]) -> Callable[P, T]: ) @functools.wraps(func) def wrapper(*args: P.args, **kwargs: P.kwargs): - guid = cast(Optional[str], kwargs.pop("guid")) + guid = cast(str | None, kwargs.pop("guid")) kwargs["app_id"] = _resolve_guid_option( - cast(Optional[bool], kwargs.get("new")), cast(Optional[str], kwargs.get("app_id")), guid + cast(bool | None, kwargs.get("new")), cast(str | None, kwargs.get("app_id")), guid ) return func(*args, **kwargs) @@ -785,7 +782,7 @@ def content_args(func: Callable[P, T]) -> Callable[P, T]: # otherwise returns None. This is so that we can pass the # non-negative (env_management_r, env_management_py) args to our API functions, # which is more consistent when writing these values to the manifest. -def env_management_callback(ctx: click.Context, param: click.Parameter, value: Optional[bool]) -> bool | None: +def env_management_callback(ctx: click.Context, param: click.Parameter, value: bool | None) -> bool | None: # eval the shorthand flag if it was provided disable_env_management = ctx.params.get("disable_env_management") if disable_env_management is not None: @@ -929,7 +926,7 @@ def _test_server_and_api(server: str, api_key: str, insecure: bool, ca_cert: str def _test_rstudio_creds(server: api.PositServer): - with cli_feedback("Checking {} credential".format(server.remote_name)): + with cli_feedback(f"Checking {server.remote_name} credential"): test_rstudio_server(server) @@ -940,9 +937,9 @@ def _test_spcs_creds(server: SPCSConnectServer): def _connect_cloud_login( account: str, - client_id: Optional[str], - client_secret: Optional[str], - url: Optional[str] = None, + client_id: str | None, + client_secret: str | None, + url: str | None = None, ) -> api.ConnectCloudServer: """Authenticate against Posit Connect Cloud and return the resulting server. @@ -974,7 +971,7 @@ def _connect_cloud_login( # A token proves the credentials are good but says nothing about the account # name, so check it here rather than letting a typo surface at deploy time. - with cli_feedback("Checking {} account".format(server.remote_name)): + with cli_feedback(f"Checking {server.remote_name} account"): with api.ConnectCloudClient(server) as client: # Keep the id: deploys address the account by id, so they neither pay for # this lookup again nor break if the account is renamed. @@ -1020,8 +1017,8 @@ def _connect_cloud_login( def bootstrap( server: str, insecure: bool, - cacert: Optional[str], - jwt_keypath: Optional[str], + cacert: str | None, + jwt_keypath: str | None, raw: bool, verbose: int, ): @@ -1091,16 +1088,16 @@ def bootstrap( def add( ctx: click.Context, name: str, - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - account: Optional[str], - token: Optional[str], - secret: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + cacert: str | None, + account: str | None, + token: str | None, + secret: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, set_default: bool, verbose: int, @@ -1180,7 +1177,7 @@ def add( set_as_default=set_default, ) verb = "Updated" if old_server else "Added" - click.echo('{} {} credential "{}" for account "{}".'.format(verb, cloud_server.remote_name, name, account)) + click.echo(f'{verb} {cloud_server.remote_name} credential "{name}" for account "{account}".') if not in_keyring: click.secho( "Note: keyring not available; credentials stored in local file (chmod 600).", @@ -1203,9 +1200,9 @@ def add( set_as_default=set_default, ) if old_server: - click.echo('Updated {} credential "{}".'.format(real_server.remote_name, name)) + click.echo(f'Updated {real_server.remote_name} credential "{name}".') else: - click.echo('Added {} credential "{}".'.format(real_server.remote_name, name)) + click.echo(f'Added {real_server.remote_name} credential "{name}".') else: if server and ("snowflakecomputing.app" in server or snowflake_connection_name): server = cast(str, server) @@ -1223,9 +1220,9 @@ def add( set_as_default=set_default, ) if old_server: - click.echo('Updated {} credential "{}".'.format(real_server_spcs.remote_name, name)) + click.echo(f'Updated {real_server_spcs.remote_name} credential "{name}".') else: - click.echo('Added {} credential "{}".'.format(real_server_spcs.remote_name, name)) + click.echo(f'Added {real_server_spcs.remote_name} credential "{name}".') else: server = cast(str, server) @@ -1321,12 +1318,12 @@ def list_servers(verbose: int): @click.pass_context def details( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, ): set_verbosity(verbose) @@ -1394,17 +1391,17 @@ def preflight( directory: str, fix: bool, new: bool, - guid: Optional[str], - app_id: Optional[str], + guid: str | None, + app_id: str | None, runtime: str, - node: Optional[str], - python: Optional[str], - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + node: str | None, + python: str | None, + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, ): from .preflight import load_preflight_app_store, run_preflight @@ -1451,8 +1448,8 @@ def preflight( @click.pass_context def remove( ctx: click.Context, - name: Optional[str], - server: Optional[str], + name: str | None, + server: str | None, verbose: int, ): set_verbosity(verbose) @@ -1513,8 +1510,8 @@ def remove( @click.pass_context def set_default( ctx: click.Context, - name: Optional[str], - server: Optional[str], + name: str | None, + server: str | None, verbose: int, ): set_verbosity(verbose) @@ -1552,7 +1549,7 @@ def server_group(): server_group.add_command(bootstrap) -def _resolve_identity_token(identity_token: Optional[str], identity_token_file: Optional[str]) -> Optional[str]: +def _resolve_identity_token(identity_token: str | None, identity_token_file: str | None) -> str | None: """Resolve the identity token from the flag/env var or a file. Returns the token string, or None if neither source was provided (in which @@ -1562,7 +1559,7 @@ def _resolve_identity_token(identity_token: Optional[str], identity_token_file: raise RSConnectException("You must specify only one of --identity-token or --identity-token-file.") if identity_token_file is not None: - with open(identity_token_file, "r") as f: + with open(identity_token_file) as f: token = f.read() elif identity_token is not None: token = sys.stdin.read() if identity_token == "-" else identity_token @@ -1580,7 +1577,7 @@ def _login_with_token_exchange( name: str, subject_token: str, insecure: bool, - ca_data: Optional[str | bytes], + ca_data: str | bytes | None, no_set_default: bool, ) -> None: """Exchange an identity token for a Connect API key and store it as the server credential.""" @@ -1674,15 +1671,15 @@ def _login_with_token_exchange( @cli_exception_handler @device_login_args("connect") def login( - server_arg: Optional[str], - server: Optional[str], - name: Optional[str], + server_arg: str | None, + server: str | None, + name: str | None, insecure: bool, - cacert: Optional[str], - identity_token: Optional[str], - identity_token_file: Optional[str], + cacert: str | None, + identity_token: str | None, + identity_token_file: str | None, use_device_code: bool, - client_id: Optional[str], + client_id: str | None, no_set_default: bool, verbose: int, ): @@ -1814,9 +1811,9 @@ def _do_login(cid: str) -> dict[str, Any]: @click.option("--verbose", "-v", count=True, help="Enable verbose output. Use -vv for very verbose (debug) output.") @cli_exception_handler def logout( - server_arg: Optional[str], - name: Optional[str], - server: Optional[str], + server_arg: str | None, + name: str | None, + server: str | None, verbose: int, ): set_verbosity(verbose) @@ -1890,8 +1887,8 @@ def logout( @click.pass_context def token( ctx: click.Context, - name: Optional[str], - server: Optional[str], + name: str | None, + server: str | None, refresh: bool, output_format: str, ): @@ -2055,12 +2052,12 @@ def quickstart( ctx: click.Context, app_type: str, project_name: str, - python_version: Optional[str], - name: Optional[str], - server: Optional[str], - api_key: Optional[str], + python_version: str | None, + name: str | None, + server: str | None, + api_key: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, ): # Resolve ``run_quickstart`` through the module at call time so tests can @@ -2079,7 +2076,7 @@ def quickstart( if ignored_options: click.echo("Server options are ignored because --python was supplied.") - def server_python_settings() -> Optional[tuple[object, str]]: + def server_python_settings() -> tuple[object, str] | None: if name and server and validation.get_parameter_source_name_from_ctx("server", ctx) == "COMMANDLINE": raise RSConnectException("-n/--name cannot be specified together with -s/--server.") if cacert: @@ -2287,39 +2284,39 @@ def _warn_on_options_ignored_by_static_notebook(ctx: click.Context, extra_files: def deploy_notebook( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - account: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + cacert: str | None, + account: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, static: bool, new: bool, - app_id: Optional[str], - title: Optional[str], - python: Optional[str], - override_python_version: Optional[str], + app_id: str | None, + title: str | None, + python: str | None, + override_python_version: str | None, force_generate: bool, - requirements_file: Optional[str], + requirements_file: str | None, verbose: int, file: str, extra_files: tuple[str, ...], hide_all_input: bool, hide_tagged_input: bool, env_vars: dict[str, str], - image: Optional[str], - disable_env_management: Optional[bool], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + disable_env_management: bool | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool, draft: bool, - visibility: Optional[str] = None, + visibility: str | None = None, no_verify: bool = False, - package_installer: Optional[PackageInstaller] = None, + package_installer: PackageInstaller | None = None, metadata: tuple[str, ...] = tuple(), no_metadata: bool = False, ): @@ -2332,9 +2329,9 @@ def deploy_notebook( app_mode = AppModes.JUPYTER_NOTEBOOK if not static else AppModes.STATIC base_dir = dirname(file) - python_interpreter: Optional[str] = None - environment: Optional[Environment] = None - r_environment: Optional[REnvironment] = None + python_interpreter: str | None = None + environment: Environment | None = None + r_environment: REnvironment | None = None if static: # The notebook is rendered locally and the bundle holds only the HTML, so Connect # never builds an environment for it. Only an interpreter to run nbconvert is needed. @@ -2490,34 +2487,34 @@ def deploy_voila( ctx: click.Context, quiet: bool, path: str, - entrypoint: Optional[str], - python: Optional[str], - override_python_version: Optional[str], + entrypoint: str | None, + python: str | None, + override_python_version: str | None, force_generate: bool, - requirements_file: Optional[str], + requirements_file: str | None, extra_files: tuple[str, ...], exclude: tuple[str, ...], - image: Optional[str], - disable_env_management: Optional[bool], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + disable_env_management: bool | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool, - title: Optional[str], + title: str | None, env_vars: dict[str, str], verbose: int, new: bool, - app_id: Optional[str], - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + app_id: str | None, + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, multi_notebook: bool, no_verify: bool, draft: bool = False, - connect_server: Optional[api.RSConnectServer] = None, # TODO: This appears to be unused - package_installer: Optional[PackageInstaller] = None, + connect_server: api.RSConnectServer | None = None, # TODO: This appears to be unused + package_installer: PackageInstaller | None = None, metadata: tuple[str, ...] = tuple(), no_metadata: bool = False, ): @@ -2602,25 +2599,25 @@ def deploy_voila( def deploy_manifest( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - account: Optional[str], - token: Optional[str], - secret: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + cacert: str | None, + account: str | None, + token: str | None, + secret: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, new: bool, - app_id: Optional[str], - title: Optional[str], + app_id: str | None, + title: str | None, verbose: int, file: str, env_vars: dict[str, str], - visibility: Optional[str], + visibility: str | None, no_verify: bool, draft: bool, metadata: tuple[str, ...] = tuple(), @@ -2706,25 +2703,25 @@ def deploy_manifest( def deploy_bundle( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - account: Optional[str], - token: Optional[str], - secret: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + cacert: str | None, + account: str | None, + token: str | None, + secret: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, new: bool, - app_id: Optional[str], - title: Optional[str], + app_id: str | None, + title: str | None, verbose: int, file: str, env_vars: dict[str, str], - visibility: Optional[str], + visibility: str | None, no_verify: bool, draft: bool, metadata: tuple[str, ...] = tuple(), @@ -2828,26 +2825,26 @@ def deploy_bundle( def deploy_pyproject( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - account: Optional[str], - token: Optional[str], - secret: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + cacert: str | None, + account: str | None, + token: str | None, + secret: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, new: bool, - app_id: Optional[str], - title: Optional[str], + app_id: str | None, + title: str | None, verbose: int, directory: str, - requirements_file: Optional[str], + requirements_file: str | None, env_vars: dict[str, str], - visibility: Optional[str], + visibility: str | None, no_verify: bool, draft: bool, exclude_renv: bool, @@ -2886,7 +2883,7 @@ def quickstart_hint() -> str: bundle_builder: Callable[..., Any] bundle_args: tuple[Any, ...] bundle_kwargs: dict[str, Any] = {} - quarto_inputs: Optional[list[str]] = None + quarto_inputs: list[str] | None = None path = directory # renv.lock detection mirrors the dedicated deploy commands; --exclude-renv @@ -3052,16 +3049,16 @@ def quickstart_hint() -> str: def deploy_git( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, new: bool, - app_id: Optional[str], - title: Optional[str], + app_id: str | None, + title: str | None, env_vars: dict[str, str], no_verify: bool, draft: bool, @@ -3190,38 +3187,38 @@ def deploy_git( def deploy_quarto( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - account: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + cacert: str | None, + account: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, new: bool, - app_id: Optional[str], - title: Optional[str], + app_id: str | None, + title: str | None, exclude: tuple[str, ...], - quarto: Optional[str], - python: Optional[str], - override_python_version: Optional[str], + quarto: str | None, + python: str | None, + override_python_version: str | None, force_generate: bool, - requirements_file: Optional[str], + requirements_file: str | None, verbose: int, file_or_directory: str, extra_files: Sequence[str], env_vars: dict[str, str], - image: Optional[str], + image: str | None, disable_env_management: bool, env_management_py: bool, env_management_r: bool, exclude_renv: bool, no_verify: bool, draft: bool, - package_installer: Optional[PackageInstaller], - visibility: Optional[str] = None, + package_installer: PackageInstaller | None, + visibility: str | None = None, metadata: tuple[str, ...] = tuple(), no_metadata: bool = False, ): @@ -3353,21 +3350,21 @@ def deploy_quarto( def deploy_tensorflow( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, new: bool, - app_id: Optional[str], - title: Optional[str], + app_id: str | None, + title: str | None, exclude: tuple[str, ...], verbose: int, directory: str, extra_files: Sequence[str], env_vars: dict[str, str], - image: Optional[str], + image: str | None, no_verify: bool, draft: bool, metadata: tuple[str, ...] = tuple(), @@ -3463,30 +3460,30 @@ def deploy_html( ctx: click.Context, quiet: bool, path: str, - entrypoint: Optional[str], + entrypoint: str | None, extra_files: tuple[str, ...], exclude: tuple[str, ...], - title: Optional[str], + title: str | None, env_vars: dict[str, str], verbose: int, new: bool, - app_id: Optional[str], - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + app_id: str | None, + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - account: Optional[str], - token: Optional[str], - secret: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + cacert: str | None, + account: str | None, + token: str | None, + secret: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, no_verify: bool, draft: bool, - visibility: Optional[str] = None, - connect_server: Optional[api.RSConnectServer] = None, + visibility: str | None = None, + connect_server: api.RSConnectServer | None = None, metadata: tuple[str, ...] = tuple(), no_metadata: bool = False, ): @@ -3558,7 +3555,7 @@ def deploy_html( ce.emit_content_url() -def resolve_requirements_file(directory: str, requirements_file: Optional[str], force_generate: bool) -> Optional[str]: +def resolve_requirements_file(directory: str, requirements_file: str | None, force_generate: bool) -> str | None: """ Determine which requirements file to use. @@ -3573,9 +3570,9 @@ def resolve_requirements_file(directory: str, requirements_file: Optional[str], def generate_deploy_python( app_mode: AppMode, - min_version: Optional[str] = None, - alias: Optional[str] = None, - desc: Optional[str] = None, + min_version: str | None = None, + alias: str | None = None, + desc: str | None = None, ): # ``alias`` defaults to the mode's primary CLI alias (declared in # ``AppModes._cli_aliases``); callers pass it explicitly only for @@ -3587,7 +3584,7 @@ def generate_deploy_python( desc = app_mode.desc() # Only surface a minimum Connect version indicator for recent (2024+) versions. - version_note = " [v{version}+]".format(version=min_version) if min_version else "" + version_note = f" [v{min_version}+]" if min_version else "" # Only advertise Connect Cloud for content types it accepts; FastAPI, # Gradio, Panel, and plain APIs are rejected at validation time. @@ -3596,15 +3593,11 @@ def generate_deploy_python( # noinspection SpellCheckingInspection @deploy.command( name=alias, - short_help="Deploy a {desc} to Posit Connect{version_note}{cloud_note} or shinyapps.io.".format( - desc=desc, - version_note=version_note, - cloud_note=cloud_note, - ), + short_help=f"Deploy a {desc} to Posit Connect{version_note}{cloud_note} or shinyapps.io.", help=( - "Deploy a {desc} module to Posit Connect{cloud_note} or shinyapps.io (if supported by the platform). " + f"Deploy a {desc} module to Posit Connect{cloud_note} or shinyapps.io (if supported by the platform). " 'The "directory" argument must refer to an existing directory that contains the application code.' - ).format(desc=desc, cloud_note=cloud_note), + ), no_args_is_help=True, ) @server_args @@ -3616,9 +3609,7 @@ def generate_deploy_python( @click.option( "--entrypoint", "-e", - help=( - "The module and executable object which serves as the entry point for the {desc} (defaults to app)" - ).format(desc=desc), + help=(f"The module and executable object which serves as the entry point for the {desc} (defaults to app)"), ) @click.option( "--exclude", @@ -3681,40 +3672,40 @@ def generate_deploy_python( def deploy_app( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - entrypoint: Optional[str], + cacert: str | None, + entrypoint: str | None, exclude: tuple[str, ...], new: bool, - app_id: Optional[str], - title: Optional[str], - python: Optional[str], - override_python_version: Optional[str], + app_id: str | None, + title: str | None, + python: str | None, + override_python_version: str | None, force_generate: bool, - requirements_file: Optional[str], + requirements_file: str | None, verbose: int, directory: str, extra_files: tuple[str, ...], - visibility: Optional[str], + visibility: str | None, env_vars: dict[str, str], - image: Optional[str], - disable_env_management: Optional[bool], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + disable_env_management: bool | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool, - account: Optional[str], - token: Optional[str], - secret: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + account: str | None, + token: str | None, + secret: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, no_verify: bool, draft: bool, - package_installer: Optional[PackageInstaller], + package_installer: PackageInstaller | None, metadata: tuple[str, ...], no_metadata: bool, ): @@ -3884,28 +3875,28 @@ def deploy_app( def deploy_nodejs( ctx: click.Context, quiet: bool, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - entrypoint: Optional[str], + cacert: str | None, + entrypoint: str | None, exclude: tuple[str, ...], new: bool, - app_id: Optional[str], - title: Optional[str], - node: Optional[str], + app_id: str | None, + title: str | None, + node: str | None, verbose: int, directory: str, extra_files: tuple[str, ...], - visibility: Optional[str], + visibility: str | None, env_vars: dict[str, str], - image: Optional[str], - env_management_node: Optional[bool], - account: Optional[str], - token: Optional[str], - secret: Optional[str], + image: str | None, + env_management_node: bool | None, + account: str | None, + token: str | None, + secret: str | None, no_verify: bool, draft: bool, metadata: tuple[str, ...], @@ -4061,21 +4052,21 @@ def write_manifest(): def write_manifest_notebook( ctx: click.Context, overwrite: bool, - python: Optional[str], - override_python_version: Optional[str], + python: str | None, + override_python_version: str | None, force_generate: bool, verbose: int, file: str, extra_files: tuple[str, ...], - image: Optional[str], - disable_env_management: Optional[bool], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + disable_env_management: bool | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool, - hide_all_input: Optional[bool] = None, - hide_tagged_input: Optional[bool] = None, - package_installer: Optional[PackageInstaller] = None, - requirements_file: Optional[str] = None, + hide_all_input: bool | None = None, + hide_tagged_input: bool | None = None, + package_installer: PackageInstaller | None = None, + requirements_file: str | None = None, ): set_verbosity(verbose) output_params(ctx, locals().items()) @@ -4199,22 +4190,22 @@ def write_manifest_notebook( def write_manifest_voila( ctx: click.Context, path: str, - entrypoint: Optional[str], + entrypoint: str | None, overwrite: bool, - python: Optional[str], - override_python_version: Optional[str], + python: str | None, + override_python_version: str | None, force_generate: bool, verbose: int, extra_files: tuple[str, ...], exclude: tuple[str, ...], - image: Optional[str], - disable_env_management: Optional[bool], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + disable_env_management: bool | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool, multi_notebook: bool, - package_installer: Optional[PackageInstaller] = None, - requirements_file: Optional[str] = None, + package_installer: PackageInstaller | None = None, + requirements_file: str | None = None, ): set_verbosity(verbose) output_params(ctx, locals().items()) @@ -4342,20 +4333,20 @@ def write_manifest_quarto( ctx: click.Context, overwrite: bool, exclude: tuple[str, ...], - quarto: Optional[str], - python: Optional[str], - override_python_version: Optional[str], + quarto: str | None, + python: str | None, + override_python_version: str | None, force_generate: bool, verbose: int, file_or_directory: str, extra_files: tuple[str, ...], - image: Optional[str], - disable_env_management: Optional[bool], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + disable_env_management: bool | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool, - package_installer: Optional[PackageInstaller], - requirements_file: Optional[str], + package_installer: PackageInstaller | None, + requirements_file: str | None, ): set_verbosity(verbose) output_params(ctx, locals().items()) @@ -4464,7 +4455,7 @@ def write_manifest_quarto( def write_manifest_pyproject( ctx: click.Context, overwrite: bool, - requirements_file: Optional[str], + requirements_file: str | None, verbose: int, exclude_renv: bool, directory: str, @@ -4528,7 +4519,7 @@ def inspect_python_environment() -> Environment: override_python_version=None, ) - environment: Optional[Environment] = None + environment: Environment | None = None if app_mode in api_modes: if app_mode == AppModes.PYTHON_SHINY: entrypoint = resolve_shiny_express_entrypoint(entrypoint, directory) @@ -4660,7 +4651,7 @@ def write_manifest_tensorflow( verbose: int, directory: str, extra_files: tuple[str, ...], - image: Optional[str], + image: str | None, ): set_verbosity(verbose) output_params(ctx, locals().items()) @@ -4682,8 +4673,8 @@ def write_manifest_tensorflow( def generate_write_manifest_python( app_mode: AppMode, - alias: Optional[str] = None, - desc: Optional[str] = None, + alias: str | None = None, + desc: str | None = None, ): # See :func:`generate_deploy_python` for the alias-resolution contract. alias = alias or app_mode.cli_alias() @@ -4693,20 +4684,18 @@ def generate_write_manifest_python( # noinspection SpellCheckingInspection @write_manifest.command( name=alias, - short_help="Create a manifest.json file for a {desc}.".format(desc=desc), + short_help=f"Create a manifest.json file for a {desc}.", help=( - "Create a manifest.json file for a {desc} for later deployment. This will create an " + f"Create a manifest.json file for a {desc} for later deployment. This will create an " 'environment file ("requirements.txt") if one does not exist. All files ' "are created in the same directory as the API code." - ).format(desc=desc), + ), ) @click.option("--overwrite", "-o", is_flag=True, help="Overwrite manifest.json, if it exists.") @click.option( "--entrypoint", "-e", - help=( - "The module and executable object which serves as the entry point for the {desc} (defaults to app)" - ).format(desc=desc), + help=(f"The module and executable object which serves as the entry point for the {desc} (defaults to app)"), ) @click.option( "--exclude", @@ -4768,21 +4757,21 @@ def generate_write_manifest_python( def manifest_writer( ctx: click.Context, overwrite: bool, - entrypoint: Optional[str], + entrypoint: str | None, exclude: tuple[str, ...], - python: Optional[str], - override_python_version: Optional[str], + python: str | None, + override_python_version: str | None, force_generate: bool, verbose: int, directory: str, extra_files: tuple[str, ...], - image: Optional[str], - disable_env_management: Optional[bool], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + disable_env_management: bool | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool, - package_installer: Optional[PackageInstaller], - requirements_file: Optional[str], + package_installer: PackageInstaller | None, + requirements_file: str | None, ): resolved_requirements_file = resolve_requirements_file(directory, requirements_file, force_generate) _write_framework_manifest( @@ -4874,14 +4863,14 @@ def manifest_writer( def write_manifest_nodejs( ctx: click.Context, overwrite: bool, - entrypoint: Optional[str], + entrypoint: str | None, exclude: tuple[str, ...], - node: Optional[str], + node: str | None, verbose: int, directory: str, extra_files: tuple[str, ...], - image: Optional[str], - env_management_node: Optional[bool], + image: str | None, + env_management_node: bool | None, ): set_verbosity(verbose) output_params(ctx, locals().items()) @@ -4912,20 +4901,20 @@ def write_manifest_nodejs( def _write_framework_manifest( ctx: click.Context, overwrite: bool, - entrypoint: Optional[str], + entrypoint: str | None, exclude: tuple[str, ...], - python: Optional[str], - override_python_version: Optional[str], + python: str | None, + override_python_version: str | None, verbose: int, directory: str, extra_files: tuple[str, ...], app_mode: AppMode, - image: Optional[str], - env_management_py: Optional[bool], - env_management_r: Optional[bool], + image: str | None, + env_management_py: bool | None, + env_management_r: bool | None, exclude_renv: bool = False, - package_installer: Optional[PackageInstaller] = None, - requirements_file: Optional[str] = None, + package_installer: PackageInstaller | None = None, + requirements_file: str | None = None, ): """ A common function for writing manifests for APIs as well as Dash, Streamlit, Bokeh, and Panel apps. @@ -5047,19 +5036,19 @@ def content(): @click.pass_context def content_search( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, published: bool, unpublished: bool, content_type: tuple[str, ...], - r_version: Optional[VersionSearchFilter], - py_version: Optional[VersionSearchFilter], - title_contains: Optional[str], - order_by: Optional[Literal["created", "last_deployed"]], + r_version: VersionSearchFilter | None, + py_version: VersionSearchFilter | None, + title_contains: str | None, + order_by: Literal["created", "last_deployed"] | None, verbose: int, ): set_verbosity(verbose) @@ -5103,12 +5092,12 @@ def content_search( @click.pass_context def content_describe( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: str, verbose: int, ): @@ -5161,12 +5150,12 @@ def content_describe( @click.pass_context def content_bundle_download( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: ContentGuidWithBundle, output: str, overwrite: bool, @@ -5228,12 +5217,12 @@ def content_bundle_download( @click.pass_context def content_get_lockfile( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: str, output: str, overwrite: bool, @@ -5293,13 +5282,13 @@ def content_get_lockfile( @click.pass_context def content_venv( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - guid: Optional[str], + cacert: str | None, + guid: str | None, env_path: str, verbose: int, ): @@ -5311,13 +5300,13 @@ def content_venv( "uv is required for `rsconnect content venv`. make sure it's available in your PATH and try again." ) - def _python_version_from_header(header: Optional[str]) -> str: + def _python_version_from_header(header: str | None) -> str: header = header or "" *_, version = header.split("python=", 1) version = version.split(".")[:2] # major.minor return ".".join(version) - def _guid_for_current_server(server_url: str) -> Optional[str]: + def _guid_for_current_server(server_url: str) -> str | None: for candidate in _get_names_to_check(os.getcwd()): deployment = AppStore(candidate).get(server_url) if deployment: @@ -5431,14 +5420,14 @@ def _guid_for_current_server(server_url: str) -> Optional[str]: @click.pass_context def content_migrate_to_connect_cloud( ctx: click.Context, - name: Optional[str], - server: Optional[str], - account: Optional[str], - client_id: Optional[str], - client_secret: Optional[str], + name: str | None, + server: str | None, + account: str | None, + client_id: str | None, + client_secret: str | None, connect_cloud: bool, content_id: str, - from_server: Optional[str], + from_server: str | None, overwrite: bool, file_or_directory: str, verbose: int, @@ -5496,12 +5485,12 @@ def repository(): @click.pass_context def repository_show( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: str, verbose: int, ): @@ -5555,12 +5544,12 @@ def repository_show( @click.pass_context def repository_delete( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: str, force: bool, verbose: int, @@ -5621,14 +5610,14 @@ def repository_delete( @click.pass_context def repository_redeploy( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: str, - ref: Optional[str], + ref: str | None, verbose: int, ): """Trigger a new deployment from the git repository. @@ -5694,12 +5683,12 @@ def build(): @click.pass_context def add_content_build( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: tuple[ContentGuidWithBundle, ...], verbose: int, ): @@ -5755,13 +5744,13 @@ def add_content_build( @click.pass_context def remove_content_build( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - guid: Optional[str], + cacert: str | None, + guid: str | None, all: bool, purge: bool, verbose: int, @@ -5811,13 +5800,13 @@ def remove_content_build( @click.pass_context def list_content_build( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], - status: Optional[str], + cacert: str | None, + status: str | None, guid: str, verbose: int, ): @@ -5856,12 +5845,12 @@ def list_content_build( @click.pass_context def get_build_history( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: str, verbose: int, ): @@ -5917,14 +5906,14 @@ def get_build_history( @click.pass_context def get_build_logs( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, guid: str, - task_id: Optional[str], + task_id: str | None, format: LogOutputFormat.All, verbose: int, ): @@ -5995,12 +5984,12 @@ def get_build_logs( @click.pass_context def start_content_build( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, parallelism: int, aborted: bool, error: bool, @@ -6051,11 +6040,11 @@ def caches(): @spcs_args def system_caches_list( name: str, - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, ): set_verbosity(verbose) @@ -6108,12 +6097,12 @@ def system_caches_list( @click.pass_context def system_caches_delete( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, language: str, version: str, @@ -6187,12 +6176,12 @@ def environment(): @click.pass_context def environment_list( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, ): set_verbosity(verbose) @@ -6227,12 +6216,12 @@ def environment_list( @click.pass_context def environment_show( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, guid: str, ): @@ -6310,18 +6299,18 @@ def environment_show( @click.pass_context def environment_add( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, image: str, - title: Optional[str], - description: Optional[str], - matching: Optional[str], - supervisor: Optional[str], + title: str | None, + description: str | None, + matching: str | None, + supervisor: str | None, python_installations: tuple[str, ...], quarto_installations: tuple[str, ...], r_installations: tuple[str, ...], @@ -6419,18 +6408,18 @@ def environment_add( @click.pass_context def environment_edit( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, guid: str, - title: Optional[str], - description: Optional[str], - matching: Optional[str], - supervisor: Optional[str], + title: str | None, + description: str | None, + matching: str | None, + supervisor: str | None, python_installations: tuple[str, ...], quarto_installations: tuple[str, ...], r_installations: tuple[str, ...], @@ -6481,12 +6470,12 @@ def environment_edit( @click.pass_context def environment_remove( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, guid: str, ): @@ -6521,12 +6510,12 @@ def integration(): @click.pass_context def integration_list( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, ): set_verbosity(verbose) @@ -6561,12 +6550,12 @@ def integration_list( @click.pass_context def integration_show( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, guid: str, ): @@ -6609,16 +6598,16 @@ def integration_show( @click.pass_context def integration_add( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, template: str, - integration_name: Optional[str], - description: Optional[str], + integration_name: str | None, + description: str | None, config: tuple[tuple[str, str], ...], allow_user: tuple[str, ...], allow_group: tuple[str, ...], @@ -6671,16 +6660,16 @@ def integration_add( @click.pass_context def integration_edit( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, guid: str, - integration_name: Optional[str], - description: Optional[str], + integration_name: str | None, + description: str | None, config: tuple[tuple[str, str], ...], allow_user: tuple[str, ...], allow_group: tuple[str, ...], @@ -6721,12 +6710,12 @@ def integration_edit( @click.pass_context def integration_remove( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, guid: str, ): @@ -6761,12 +6750,12 @@ def integration_templates(): @click.pass_context def integration_templates_list( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, ): set_verbosity(verbose) @@ -6800,12 +6789,12 @@ def integration_templates_list( @click.pass_context def integration_templates_show( ctx: click.Context, - name: Optional[str], - server: Optional[str], - api_key: Optional[str], - snowflake_connection_name: Optional[str], + name: str | None, + server: str | None, + api_key: str | None, + snowflake_connection_name: str | None, insecure: bool, - cacert: Optional[str], + cacert: str | None, verbose: int, template_id: str, ): diff --git a/rsconnect/metadata.py b/rsconnect/metadata.py index 077c90951..d9a782c14 100644 --- a/rsconnect/metadata.py +++ b/rsconnect/metadata.py @@ -13,21 +13,18 @@ import stat import sys from contextlib import suppress -from datetime import datetime, timezone +from datetime import datetime, UTC from io import BufferedWriter from os.path import abspath, basename, dirname, exists, join from threading import Lock from typing import ( TYPE_CHECKING, - Callable, Generic, - Mapping, NotRequired, - Optional, TypedDict, TypeVar, - Union, ) +from collections.abc import Callable, Mapping from urllib.parse import urlparse if TYPE_CHECKING: @@ -120,7 +117,7 @@ class DataStore(Generic[T]): def __init__( self, primary_path: str, - secondary_path: Optional[str] = None, + secondary_path: str | None = None, chmod: bool = False, *, autoload: bool = True, @@ -404,23 +401,23 @@ def __init__( name: str, url: str, from_store: bool, - api_key: Optional[str] = None, - snowflake_connection_name: Optional[str] = None, - insecure: Optional[bool] = None, - ca_data: Optional[str] = None, - account_name: Optional[str] = None, - token: Optional[str] = None, - secret: Optional[str] = None, - oauth_client_id: Optional[str] = None, - oauth_access_token: Optional[str] = None, - oauth_refresh_token: Optional[str] = None, - oauth_token_expiry: Optional[float] = None, - connect_cloud_account_name: Optional[str] = None, - connect_cloud_account_id: Optional[str] = None, - connect_cloud_client_id: Optional[str] = None, - connect_cloud_client_secret: Optional[str] = None, - connect_cloud_access_token: Optional[str] = None, - connect_cloud_refresh_token: Optional[str] = None, + api_key: str | None = None, + snowflake_connection_name: str | None = None, + insecure: bool | None = None, + ca_data: str | None = None, + account_name: str | None = None, + token: str | None = None, + secret: str | None = None, + oauth_client_id: str | None = None, + oauth_access_token: str | None = None, + oauth_refresh_token: str | None = None, + oauth_token_expiry: float | None = None, + connect_cloud_account_name: str | None = None, + connect_cloud_account_id: str | None = None, + connect_cloud_client_id: str | None = None, + connect_cloud_client_secret: str | None = None, + connect_cloud_access_token: str | None = None, + connect_cloud_refresh_token: str | None = None, ): self.name = name self.url = url @@ -480,7 +477,7 @@ def get_by_url(self, url: str): return self._get_connect_cloud_server(target) return self._get_by_value_attr("url", target) - def saved_entry(self, name: Optional[str], url: str) -> Optional[ServerDataDict]: + def saved_entry(self, name: str | None, url: str) -> ServerDataDict | None: """The entry a server in hand came from: by its nickname, else by its URL. A one-shot target has no nickname, and neither does one resolved before the @@ -491,7 +488,7 @@ def saved_entry(self, name: Optional[str], url: str) -> Optional[ServerDataDict] entry = self.get_by_url(url) return entry - def has_connect_cloud_account(self, url: Optional[str]) -> bool: + def has_connect_cloud_account(self, url: str | None) -> bool: """Whether any Posit Connect Cloud credential is saved for this URL. Callers use this to decide whether the account has to be supplied on the @@ -540,7 +537,7 @@ def _get_connect_cloud_server(self, url: str): "use client credentials directly." % saved ) - def _connect_cloud_secrets(self, entry: ServerDataDict) -> tuple[Optional[str], Optional[str], Optional[str]]: + def _connect_cloud_secrets(self, entry: ServerDataDict) -> tuple[str | None, str | None, str | None]: """A Posit Connect Cloud entry's secrets, as (access, refresh, client secret). `rsconnect add` and token refresh store these in the system keyring when @@ -571,7 +568,7 @@ def get_all_servers(self): """ return self._get_sorted_values(lambda s: s.get("name") or "") - def get_default(self) -> Optional[ServerDataDict]: + def get_default(self) -> ServerDataDict | None: """Return the entry marked as default, or None.""" for entry in self._data.values(): if entry.get("default"): @@ -596,23 +593,23 @@ def set( self, name: str, url: str, - api_key: Optional[str] = None, - snowflake_connection_name: Optional[str] = None, - insecure: Optional[bool] = False, - ca_data: Optional[str] = None, - account_name: Optional[str] = None, - token: Optional[str] = None, - secret: Optional[str] = None, - oauth_client_id: Optional[str] = None, - oauth_access_token: Optional[str] = None, - oauth_refresh_token: Optional[str] = None, - oauth_token_expiry: Optional[float] = None, - connect_cloud_account_name: Optional[str] = None, - connect_cloud_account_id: Optional[str] = None, - connect_cloud_client_id: Optional[str] = None, - connect_cloud_client_secret: Optional[str] = None, - connect_cloud_access_token: Optional[str] = None, - connect_cloud_refresh_token: Optional[str] = None, + api_key: str | None = None, + snowflake_connection_name: str | None = None, + insecure: bool | None = False, + ca_data: str | None = None, + account_name: str | None = None, + token: str | None = None, + secret: str | None = None, + oauth_client_id: str | None = None, + oauth_access_token: str | None = None, + oauth_refresh_token: str | None = None, + oauth_token_expiry: float | None = None, + connect_cloud_account_name: str | None = None, + connect_cloud_account_id: str | None = None, + connect_cloud_client_id: str | None = None, + connect_cloud_client_secret: str | None = None, + connect_cloud_access_token: str | None = None, + connect_cloud_refresh_token: str | None = None, set_as_default: bool = False, ): """ @@ -723,9 +720,9 @@ def remove_by_url(self, url: str): def update_oauth_tokens( self, name: str, - access_token: Optional[str], - refresh_token: Optional[str], - expiry: Optional[float], + access_token: str | None, + refresh_token: str | None, + expiry: float | None, ) -> None: """Update (or clear) stored OAuth token fields for an existing server entry.""" entry = self._get_by_key(name) @@ -742,7 +739,7 @@ def update_oauth_tokens( updated.pop("oauth_token_expiry", None) # type: ignore[misc] self._set(name, updated) - def resolve(self, name: Optional[str], url: Optional[str]) -> ServerData: + def resolve(self, name: str | None, url: str | None) -> ServerData: """ This function will resolve the given inputs into a set of server information. It assumes that either `name` or `url` is provided. @@ -819,7 +816,7 @@ class AppMetadata(TypedDict): app_url: str app_id: str # Posit Connect Cloud and shinyapps.io identify content by id alone. - app_guid: Optional[str] + app_guid: str | None title: str app_mode: str app_store_version: int @@ -853,7 +850,7 @@ class AppStore(DataStore[AppMetadata]): def __init__(self, app_file: str, version: int = 1, *, autoload: bool = True, strict_read: bool = False): base_name = str(basename(app_file).rsplit(".", 1)[0]) + ".json" - super(AppStore, self).__init__( + super().__init__( join(dirname(app_file), "rsconnect-python", base_name), join(config_dirname(), "applications", sha1(abspath(app_file)) + ".json"), autoload=autoload, @@ -881,7 +878,7 @@ def set( filename: str, app_url: str, app_id: str, - app_guid: Optional[str], + app_guid: str | None, title: str, app_mode: AppMode | str, ): @@ -920,7 +917,7 @@ def remove(self, server_url: str) -> bool: """ return self._remove_by_key(server_url) - def resolve(self, server: str, app_id: Optional[str], app_mode: Optional[AppMode]): + def resolve(self, server: str, app_id: str | None, app_mode: AppMode | None): metadata = self.get(server) if metadata is None: logger.debug("No previous deployment to this server was found; this will be a new deployment.") @@ -991,7 +988,7 @@ class ContentBuildStore(DataStore[dict[str, object]]): def __init__( self, - server: Union[RSConnectServer, SPCSConnectServer], + server: RSConnectServer | SPCSConnectServer, base_dir: str = os.getenv("CONNECT_CONTENT_BUILD_DIR", DEFAULT_BUILD_DIR), ): # This type declaration is a bit of a hack. It is needed because data model used @@ -1001,7 +998,7 @@ def __init__( self._base_dir = os.path.abspath(base_dir) self._build_logs_dir = join(self._base_dir, "logs", _normalize_server_url(server.url)) self._build_state_file = join(self._base_dir, "%s.json" % _normalize_server_url(server.url)) - super(ContentBuildStore, self).__init__(self._build_state_file, chmod=True) + super().__init__(self._build_state_file, chmod=True) def aborted(self) -> bool: return ContentBuildStore._BUILD_ABORTED @@ -1015,7 +1012,7 @@ def ensure_logs_dir(self, guid: str) -> None: if self._chmod: os.chmod(log_dir, 0o700) - def get_build_log(self, guid: str, task_id: Optional[str] = None) -> str | None: + def get_build_log(self, guid: str, task_id: str | None = None) -> str | None: """ Returns the path to the build log file. This method does not check whether the file exists if a task_id is provided. @@ -1039,7 +1036,7 @@ def get_build_history(self, guid: str) -> list[dict[str, str]]: history: list[dict[str, str]] = [] for f in log_files: task_id = basename(f).split(".log")[0] - t = datetime.fromtimestamp(os.path.getctime(f), tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S%z") + t = datetime.fromtimestamp(os.path.getctime(f), tz=UTC).strftime("%Y-%m-%d %H:%M:%S%z") history.append({"time": t, "task_id": task_id}) history.sort(key=lambda x: x["time"]) return history @@ -1127,7 +1124,7 @@ def update_content_item_last_build_time(self, guid: str, defer_save: bool = Fals """ with self._lock: content = self.get_content_item(guid) - content["rsconnect_last_build_time"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + content["rsconnect_last_build_time"] = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ") if not defer_save: self.save() @@ -1161,7 +1158,7 @@ def set_content_item_last_build_task_result(self, guid: str, task: TaskStatusV1, if not defer_save: self.save() - def get_content_items(self, status: Optional[str] = None) -> list[ContentItemWithBuildState]: + def get_content_items(self, status: str | None = None) -> list[ContentItemWithBuildState]: """ Get all the content items that are tracked for build in the state-file. :param status: Filter results by build status diff --git a/rsconnect/models.py b/rsconnect/models.py index 951b9001b..d6c439202 100644 --- a/rsconnect/models.py +++ b/rsconnect/models.py @@ -7,7 +7,8 @@ import fnmatch import pathlib import re -from typing import Callable, Literal, NotRequired, Optional, TypedDict, cast +from typing import Literal, NotRequired, TypedDict, cast +from collections.abc import Callable import click import semver @@ -45,7 +46,7 @@ def __init__( ordinal: int, name: AppModes.Modes, text: str, - ext: Optional[str] = None, + ext: str | None = None, ): self._ordinal = ordinal self._name: AppModes.Modes = name @@ -64,7 +65,7 @@ def desc(self): def extension(self): return self._ext - def cli_alias(self) -> Optional[str]: + def cli_alias(self) -> str | None: """Return the primary CLI alias for this mode, or ``None`` if absent. "Primary" is the first key declared in :data:`AppModes._cli_aliases` @@ -238,7 +239,7 @@ def get_by_name(cls, name: str, return_unknown: bool = False) -> AppMode: return cls._find_by(lambda mode: mode.name() == name, "named %s" % name, return_unknown) @classmethod - def get_by_extension(cls, extension: Optional[str], return_unknown: bool = False) -> AppMode: + def get_by_extension(cls, extension: str | None, return_unknown: bool = False) -> AppMode: """Get an app mode by its associated extension""" # We can't allow a lookup by None since some modes have that for an extension. if extension is None: @@ -257,7 +258,7 @@ def get_by_cloud_name(cls, name: str) -> AppMode: return cls._cloud_to_connect_modes.get(name, cls.UNKNOWN) @classmethod - def get_connect_cloud_content_type(cls, mode: AppMode) -> Optional[str]: + def get_connect_cloud_content_type(cls, mode: AppMode) -> str | None: """The Posit Connect Cloud content type for an app mode, or None. None means Connect Cloud cannot host that kind of content. @@ -294,7 +295,7 @@ def _find_by(cls, predicate: Callable[[AppMode], bool], message: str, return_unk raise ValueError("No app mode %s" % message) -class GlobMatcher(object): +class GlobMatcher: """ A simplified means of matching a path against a glob pattern. The key limitation is that we support at most one occurrence of the `**` pattern. @@ -381,7 +382,7 @@ def items_match(i1: int, i2: int): return pattern_index == wildcard_index -class GlobSet(object): +class GlobSet: """ Matches against a set of `GlobMatcher` patterns """ @@ -405,23 +406,23 @@ def matches(self, path: str): class StrippedStringParamType(StringParamType): name = "StrippedString" - def convert(self, value: str, param: Optional[click.Parameter], ctx: Optional[click.Context]) -> str: - value = super(StrippedStringParamType, self).convert(value, param, ctx) + def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str: + value = super().convert(value, param, ctx) return value.strip("\"'") class ContentGuidParamType(StrippedStringParamType): name = "GUID" - def convert(self, value: str, param: Optional[click.Parameter], ctx: Optional[click.Context]) -> str: - value = super(ContentGuidParamType, self).convert(value, param, ctx) + def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None) -> str: + value = super().convert(value, param, ctx) if not is_content_guid(value): self.fail("%r is not a content GUID." % value, param, ctx) return value -class ContentGuidWithBundle(object): - def __init__(self, guid: str, bundle_id: Optional[str] = None): +class ContentGuidWithBundle: + def __init__(self, guid: str, bundle_id: str | None = None): self.guid = guid self.bundle_id = bundle_id @@ -437,13 +438,13 @@ class ContentGuidWithBundleParamType(StrippedStringParamType): def convert( # pyright: ignore[reportIncompatibleMethodOverride] self, value: str | ContentGuidWithBundle, - param: Optional[click.Parameter], - ctx: Optional[click.Context], + param: click.Parameter | None, + ctx: click.Context | None, ): if isinstance(value, ContentGuidWithBundle): return value if isinstance(value, str): - value = super(ContentGuidWithBundleParamType, self).convert(value, param, ctx) + value = super().convert(value, param, ctx) m = re.match(_content_guid_pattern, value) if m is not None: guid_with_bundle = ContentGuidWithBundle(m.group(1)) @@ -511,7 +512,7 @@ class ContentItemV1(TypedDict): ComparisonOperator = Literal[">", "<", ">=", "<=", "=", "=="] -class VersionSearchFilter(object): +class VersionSearchFilter: def __init__( self, name: VersionProgramName, @@ -539,8 +540,8 @@ def __init__(self, key: VersionProgramName): def convert( self, value: str | VersionSearchFilter, - param: Optional[click.Parameter], - ctx: Optional[click.Context], + param: click.Parameter | None, + ctx: click.Context | None, ): if isinstance(value, VersionSearchFilter): return value @@ -790,8 +791,8 @@ class KeyValueParamType(ParamType): def convert( self, value: str | tuple[str, str], - param: Optional[click.Parameter], - ctx: Optional[click.Context], + param: click.Parameter | None, + ctx: click.Context | None, ) -> tuple[str, str]: if isinstance(value, tuple): return value diff --git a/rsconnect/oauth.py b/rsconnect/oauth.py index 3ddc5d7d3..eff9c1788 100644 --- a/rsconnect/oauth.py +++ b/rsconnect/oauth.py @@ -18,7 +18,8 @@ import webbrowser from contextlib import contextmanager from http.server import BaseHTTPRequestHandler, HTTPServer as _HTTPServer -from typing import Any, Dict, Generator, Iterable, Mapping, Optional, Tuple, cast +from typing import Any, cast +from collections.abc import Generator, Iterable, Mapping from urllib.parse import parse_qs, urlencode, urlparse, urlunparse import click @@ -73,7 +74,7 @@ class InvalidGrantError(RSConnectException): server's ``error_description`` is kept in ``description`` when it sends one. """ - def __init__(self, description: Optional[str] = None) -> None: + def __init__(self, description: str | None = None) -> None: self.description = description super().__init__("The OAuth grant is invalid, expired, or has been revoked.") @@ -105,21 +106,21 @@ def _unwrap_json_response(response: Any) -> dict[str, Any]: """ if isinstance(response, HTTPResponse): if response.status and 200 <= response.status < 300 and isinstance(response.json_data, dict): - return cast(Dict[str, Any], response.json_data) + return cast(dict[str, Any], response.json_data) _check_oauth_error_response(response) raise RSConnectException(f"OAuth request failed: HTTP {response.status}.") if isinstance(response, dict): - return cast(Dict[str, Any], response) + return cast(dict[str, Any], response) raise RSConnectException("Unexpected OAuth response format.") -def _oauth_response_data(response: Any) -> tuple[Optional[dict[str, Any]], Optional[int]]: +def _oauth_response_data(response: Any) -> tuple[dict[str, Any] | None, int | None]: """Return an OAuth response's JSON object and HTTP status when available.""" if isinstance(response, HTTPResponse): data = response.json_data - return (cast(Dict[str, Any], data) if isinstance(data, dict) else None, response.status) + return (cast(dict[str, Any], data) if isinstance(data, dict) else None, response.status) if isinstance(response, dict): - return cast(Dict[str, Any], response), 200 + return cast(dict[str, Any], response), 200 return None, None @@ -137,9 +138,9 @@ def _post_oauth_form_request( path: str, params: Mapping[str, str], insecure: bool = False, - ca_data: Optional[str | bytes] = None, - request_timeout: Optional[float] = None, - request_deadline: Optional[float] = None, + ca_data: str | bytes | None = None, + request_timeout: float | None = None, + request_deadline: float | None = None, *, suppress_response_logging: bool = False, ) -> Any: @@ -165,9 +166,9 @@ def _post_oauth_form_request( def discover_oauth_metadata( url: str, insecure: bool = False, - ca_data: Optional[str | bytes] = None, - request_timeout: Optional[float] = None, - request_deadline: Optional[float] = None, + ca_data: str | bytes | None = None, + request_timeout: float | None = None, + request_deadline: float | None = None, *, suppress_response_logging: bool = False, ) -> dict[str, Any]: @@ -204,9 +205,9 @@ def register_client( metadata: dict[str, Any], url: str, insecure: bool = False, - ca_data: Optional[str | bytes] = None, - request_timeout: Optional[float] = None, - request_deadline: Optional[float] = None, + ca_data: str | bytes | None = None, + request_timeout: float | None = None, + request_deadline: float | None = None, *, suppress_response_logging: bool = False, ) -> str: @@ -249,7 +250,7 @@ def register_client( return str(data["client_id"]) -def generate_pkce_pair() -> Tuple[str, str]: +def generate_pkce_pair() -> tuple[str, str]: """Generate a PKCE code_verifier and code_challenge (S256).""" code_verifier = secrets.token_urlsafe(96)[:96] digest = hashlib.sha256(code_verifier.encode("ascii")).digest() @@ -264,7 +265,7 @@ def _exchange_code_for_token( code_verifier: str, redirect_uri: str, insecure: bool = False, - ca_data: Optional[str | bytes] = None, + ca_data: str | bytes | None = None, ) -> dict[str, Any]: """Exchange an authorization code for tokens.""" token_endpoint = str(metadata["token_endpoint"]) @@ -297,7 +298,7 @@ def _exchange_code_for_token( class _CallbackHandler(BaseHTTPRequestHandler): """HTTP request handler for the OAuth redirect callback.""" - result_queue: queue.Queue[Tuple[str, Optional[str], Optional[str]]] + result_queue: queue.Queue[tuple[str, str | None, str | None]] def do_GET(self) -> None: # noqa: N802 qs = parse_qs(urlparse(self.path).query) @@ -330,7 +331,7 @@ def login_with_browser( client_id: str, metadata: dict[str, Any], insecure: bool = False, - ca_data: Optional[str | bytes] = None, + ca_data: str | bytes | None = None, ) -> dict[str, Any]: """Perform OAuth Authorization Code + PKCE flow via browser. @@ -340,7 +341,7 @@ def login_with_browser( code_verifier, code_challenge = generate_pkce_pair() state = secrets.token_urlsafe(32) - result_queue: queue.Queue[Tuple[str, Optional[str], Optional[str]]] = queue.Queue() + result_queue: queue.Queue[tuple[str, str | None, str | None]] = queue.Queue() callback_server = _HTTPServer(("127.0.0.1", 0), _CallbackHandler) port = callback_server.server_address[1] @@ -399,8 +400,8 @@ def login_with_device_code( client_id: str, metadata: dict[str, Any], insecure: bool = False, - ca_data: Optional[str | bytes] = None, - scope: Optional[str] = None, + ca_data: str | bytes | None = None, + scope: str | None = None, open_browser: bool = True, ) -> dict[str, Any]: """Perform OAuth Device Code flow. @@ -461,8 +462,8 @@ def _poll_for_device_token( interval: int, expires_in: int, insecure: bool = False, - ca_data: Optional[str | bytes] = None, - scope: Optional[str] = None, + ca_data: str | bytes | None = None, + scope: str | None = None, ) -> dict[str, Any]: """Poll the token endpoint for device code completion.""" token_endpoint = str(metadata["token_endpoint"]) @@ -515,10 +516,10 @@ def refresh_access_token( client_id: str, refresh_token: str, insecure: bool = False, - ca_data: Optional[str | bytes] = None, - scope: Optional[str] = None, - request_timeout: Optional[float] = None, - request_deadline: Optional[float] = None, + ca_data: str | bytes | None = None, + scope: str | None = None, + request_timeout: float | None = None, + request_deadline: float | None = None, *, suppress_response_logging: bool = False, ) -> dict[str, Any]: @@ -554,9 +555,9 @@ def request_client_credentials_token( token_endpoint: str, client_id: str, client_secret: str, - scope: Optional[str] = None, + scope: str | None = None, insecure: bool = False, - ca_data: Optional[str | bytes] = None, + ca_data: str | bytes | None = None, ) -> dict[str, Any]: """Request an access token using the OAuth client credentials grant (RFC 6749 4.4). @@ -583,9 +584,9 @@ def _post_token_request( token_endpoint: str, params: dict[str, str], insecure: bool = False, - ca_data: Optional[str | bytes] = None, - request_timeout: Optional[float] = None, - request_deadline: Optional[float] = None, + ca_data: str | bytes | None = None, + request_timeout: float | None = None, + request_deadline: float | None = None, *, suppress_response_logging: bool = False, ) -> dict[str, Any]: @@ -617,7 +618,7 @@ def exchange_token_for_api_key( url: str, subject_token: str, insecure: bool = False, - ca_data: Optional[str | bytes] = None, + ca_data: str | bytes | None = None, ) -> str: """Exchange an OIDC identity token for a short-lived Connect API key (RFC 8693). @@ -689,7 +690,7 @@ def exchange_token_for_api_key( raise _token_exchange_error(status, data) -def _token_exchange_error(status: Optional[int], data: dict[str, Any]) -> RSConnectException: +def _token_exchange_error(status: int | None, data: dict[str, Any]) -> RSConnectException: """Translate a failed token-exchange response into an actionable exception.""" error = str(data.get("error", "")) if data else "" description = str(data.get("error_description", "")) if data else "" @@ -747,7 +748,7 @@ def _no_keyring_errors() -> tuple[type[BaseException], ...]: return (NoKeyringError,) -def keyring_store_values(key: str, values: Mapping[str, Optional[str]]) -> bool: +def keyring_store_values(key: str, values: Mapping[str, str | None]) -> bool: """Store credential values in the system keyring, deleting the empty ones. Entries are named ":". A Posit Connect caller passes the bare @@ -797,7 +798,7 @@ def keyring_store_values(key: str, values: Mapping[str, Optional[str]]) -> bool: return False -def keyring_read_value(key: str, field: str) -> Tuple[bool, Optional[str]]: +def keyring_read_value(key: str, field: str) -> tuple[bool, str | None]: """Retrieve one credential value, saying whether the keyring could be read. A caller that decides what to write based on what is already stored needs to @@ -820,7 +821,7 @@ def keyring_read_value(key: str, field: str) -> Tuple[bool, Optional[str]]: return False, None -def keyring_get_value(key: str, field: str) -> Optional[str]: +def keyring_get_value(key: str, field: str) -> str | None: """Retrieve one credential value from the system keyring, or None.""" return keyring_read_value(key, field)[1] @@ -874,7 +875,7 @@ def keyring_delete_values(key: str, fields: Iterable[str]) -> bool: return False -def keyring_store_token(key: str, access_token: Optional[str], refresh_token: Optional[str]) -> bool: +def keyring_store_token(key: str, access_token: str | None, refresh_token: str | None) -> bool: """Store OAuth tokens in the system keyring. Returns True on success, False if keyring is not available. @@ -882,7 +883,7 @@ def keyring_store_token(key: str, access_token: Optional[str], refresh_token: Op return keyring_store_values(key, {ACCESS_TOKEN_FIELD: access_token, REFRESH_TOKEN_FIELD: refresh_token}) -def keyring_get_tokens(key: str) -> Tuple[Optional[str], Optional[str]]: +def keyring_get_tokens(key: str) -> tuple[str | None, str | None]: """Retrieve OAuth tokens from the system keyring. Returns (access_token, refresh_token), or (None, None) if unavailable. @@ -895,7 +896,7 @@ def keyring_delete_tokens(key: str) -> None: keyring_delete_values(key, (ACCESS_TOKEN_FIELD, REFRESH_TOKEN_FIELD)) -def stored_tokens(server_url: str, server_name: Optional[str] = None) -> Tuple[Optional[str], Optional[str]]: +def stored_tokens(server_url: str, server_name: str | None = None) -> tuple[str | None, str | None]: """The (access_token, refresh_token) that `rsconnect login` stored for a Posit Connect server. The keyring is where a login stores its tokens; the server's saved entry holds @@ -915,11 +916,11 @@ def stored_tokens(server_url: str, server_name: Optional[str] = None) -> Tuple[O def refresh_stored_tokens( server_url: str, client_id: str, - server_name: Optional[str] = None, + server_name: str | None = None, insecure: bool = False, - ca_data: Optional[str | bytes] = None, + ca_data: str | bytes | None = None, *, - rejected_access_token: Optional[str], + rejected_access_token: str | None, ) -> str: """Exchange the stored refresh token for a new access token, store both, and return the access token. @@ -965,7 +966,7 @@ def refresh_stored_tokens( def _replace_deleted_client( - server_url: str, server_name: Optional[str], insecure: bool, ca_data: Optional[str | bytes] + server_url: str, server_name: str | None, insecure: bool, ca_data: str | bytes | None ) -> None: """Clear the tokens of an OAuth client the server deleted, and register a new client in its place.""" from .metadata import ServerStore diff --git a/rsconnect/preflight.py b/rsconnect/preflight.py index 9d9ed6e8e..2e4f48f14 100644 --- a/rsconnect/preflight.py +++ b/rsconnect/preflight.py @@ -10,7 +10,8 @@ import sys import tomllib from pathlib import Path -from typing import Any, List, Mapping, Optional, Tuple, Union, cast +from typing import Any, cast +from collections.abc import Mapping from packaging.specifiers import InvalidSpecifier, SpecifierSet from packaging.version import InvalidVersion, Version @@ -32,7 +33,7 @@ _APP_STORE_READ_ERRORS = (OSError, ValueError, RecursionError, AttributeError, TypeError) -def _invalid_declared_metadata(project_path: Path) -> Optional[str]: +def _invalid_declared_metadata(project_path: Path) -> str | None: for filename, metadata_file in lookup_metadata_file(project_path): parser = get_python_version_requirement_parser(metadata_file) try: @@ -51,7 +52,7 @@ def _invalid_declared_metadata(project_path: Path) -> Optional[str]: return None -def _project_constraint(project: str, warnings: list[str]) -> tuple[Optional[str], Optional[str]]: +def _project_constraint(project: str, warnings: list[str]) -> tuple[str | None, str | None]: project_path = Path(project) for filename in _METADATA_FILES: if (project_path / filename).is_symlink(): @@ -80,7 +81,7 @@ def _server_python_versions(settings: Any) -> tuple[list[str], list[str], bool, if not isinstance(raw_installations, list): return [], [], False, False - installations = cast(List[Any], raw_installations) + installations = cast(list[Any], raw_installations) installed: list[str] = [] publishable: list[str] = [] flags_complete = True @@ -115,7 +116,7 @@ def _minor(version: str) -> tuple[int, int]: return release[0], release[1] -def _pick_python_pin(versions: list[str], local_python: str) -> Optional[str]: +def _pick_python_pin(versions: list[str], local_python: str) -> str | None: minors = sorted({_minor(version) for version in versions}) if not minors: return None @@ -130,13 +131,13 @@ def _pick_python_pin(versions: list[str], local_python: str) -> Optional[str]: def _local_publishable( local_python: str, versions: list[str], has_installations: bool, flags_complete: bool -) -> Optional[bool]: +) -> bool | None: if any(_minor(version) == _minor(local_python) for version in versions): return True return False if has_installations and flags_complete else None -def _constraint_compatibility(constraint: Optional[str], versions: list[str]) -> str: +def _constraint_compatibility(constraint: str | None, versions: list[str]) -> str: if constraint is None: return "unconstrained" if not versions: @@ -179,7 +180,7 @@ def load_preflight_app_store(path: str) -> AppStore: return store -def _read_app_store_record(store: Any, server_key: str) -> tuple[Optional[Mapping[str, Any]], Optional[str]]: +def _read_app_store_record(store: Any, server_key: str) -> tuple[Mapping[str, Any] | None, str | None]: try: record = store.get(server_key) except _APP_STORE_READ_ERRORS as err: @@ -191,7 +192,7 @@ def _read_app_store_record(store: Any, server_key: str) -> tuple[Optional[Mappin return cast(Mapping[str, Any], record), None -def _read_deployment_records(executor: RSConnectExecutor, target: str) -> tuple[list[Mapping[str, Any]], Optional[str]]: +def _read_deployment_records(executor: RSConnectExecutor, target: str) -> tuple[list[Mapping[str, Any]], str | None]: directory = os.path.isdir(target) module_file = fake_module_file_from_directory(target) if directory else None executor_module = fake_module_file_from_directory(executor.path) @@ -215,7 +216,7 @@ def _read_deployment_records(executor: RSConnectExecutor, target: str) -> tuple[ return records, None -def _file_deployment_records(source: Path, server_key: str) -> tuple[list[Mapping[str, Any]], Optional[str]]: +def _file_deployment_records(source: Path, server_key: str) -> tuple[list[Mapping[str, Any]], str | None]: records: list[Mapping[str, Any]] = [] try: for app_file in (str(source), fake_module_file_from_directory(str(source))): @@ -229,9 +230,7 @@ def _file_deployment_records(source: Path, server_key: str) -> tuple[list[Mappin return records, None -def _directory_file_deployments( - executor: RSConnectExecutor, target: str -) -> tuple[list[Mapping[str, Any]], Optional[str]]: +def _directory_file_deployments(executor: RSConnectExecutor, target: str) -> tuple[list[Mapping[str, Any]], str | None]: records: list[Mapping[str, Any]] = [] server_key = executor.record_server_key() try: @@ -247,7 +246,7 @@ def _directory_file_deployments( return records, None -def _target_from_records(records: list[Mapping[str, Any]]) -> tuple[bool, Optional[str], Optional[str]]: +def _target_from_records(records: list[Mapping[str, Any]]) -> tuple[bool, str | None, str | None]: if len(records) > 1: return True, None, "Multiple local deployment records match this target." if not records: @@ -258,7 +257,7 @@ def _target_from_records(records: list[Mapping[str, Any]]) -> tuple[bool, Option return True, record_id, None -def _saved_deployment_target(executor: RSConnectExecutor, target: str) -> tuple[bool, Optional[str], Optional[str]]: +def _saved_deployment_target(executor: RSConnectExecutor, target: str) -> tuple[bool, str | None, str | None]: records, issue = _read_deployment_records(executor, target) if issue: return True, None, issue @@ -271,7 +270,7 @@ def _saved_deployment_target(executor: RSConnectExecutor, target: str) -> tuple[ return _target_from_records(records) -def _deployment_target(executor: RSConnectExecutor, target: str) -> tuple[bool, Optional[str], Optional[str]]: +def _deployment_target(executor: RSConnectExecutor, target: str) -> tuple[bool, str | None, str | None]: if executor.new: return False, None, None if executor.app_id: @@ -281,7 +280,7 @@ def _deployment_target(executor: RSConnectExecutor, target: str) -> tuple[bool, def _current_python( client: RSConnectClient, app_id: str, warnings: list[str], actions: list[str] -) -> tuple[Optional[str], bool]: +) -> tuple[str | None, bool]: try: content = client.content_get(app_id) except RSConnectException as err: @@ -308,13 +307,13 @@ def _current_python( def _existing_content( client: RSConnectClient, exists: bool, - app_id: Optional[str], - constraint: Optional[str], + app_id: str | None, + constraint: str | None, installed_versions: list[str], warnings: list[str], actions: list[str], ) -> tuple[dict[str, Any], bool]: - current_python: Optional[str] = None + current_python: str | None = None content_readable = True if exists and app_id: current_python, content_readable = _current_python(client, app_id, warnings, actions) @@ -349,14 +348,14 @@ def _write_python_pin(project: str, version: str) -> bool: def _recommend_python_pin( project: str, is_new: bool, - constraint: Optional[str], - invalid_metadata: Optional[str], + constraint: str | None, + invalid_metadata: str | None, versions: list[str], local_python: str, fix: bool, warnings: list[str], actions: list[str], -) -> tuple[Optional[str], Optional[str], list[str], Optional[str]]: +) -> tuple[str | None, str | None, list[str], str | None]: if not is_new or constraint is not None or invalid_metadata: return constraint, None, [], invalid_metadata recommendation = _pick_python_pin(versions, local_python) @@ -385,10 +384,10 @@ def _recommend_python_pin( def _new_content_status( - constraint: Optional[str], + constraint: str | None, publishable_versions: list[str], flags_complete: bool, - local_publishable: Optional[bool], + local_publishable: bool | None, ) -> str: if constraint is not None: compatibility = _constraint_compatibility(constraint, publishable_versions) @@ -404,12 +403,12 @@ def _new_content_status( def _status( is_new: bool, - constraint: Optional[str], - invalid_metadata: Optional[str], + constraint: str | None, + invalid_metadata: str | None, installed_versions: list[str], publishable_versions: list[str], flags_complete: bool, - local_publishable: Optional[bool], + local_publishable: bool | None, ) -> str: if invalid_metadata or not installed_versions: return "unknown" @@ -422,7 +421,7 @@ def _status( def _availability_advice( - settings_error: Optional[str], + settings_error: str | None, installed_versions: list[str], publishable_versions: list[str], has_installations: bool, @@ -431,7 +430,7 @@ def _availability_advice( warnings: list[str], actions: list[str], ) -> None: - action: Optional[str] = None + action: str | None = None if settings_error: warnings.append(f"Could not read server Python settings: {settings_error}") action = "Check the server's Python installations before publishing." @@ -452,7 +451,7 @@ def _availability_advice( actions.append(action) -def _incompatible_advice(is_new: bool, constraint: Optional[str], warnings: list[str], actions: list[str]) -> None: +def _incompatible_advice(is_new: bool, constraint: str | None, warnings: list[str], actions: list[str]) -> None: if not is_new: warnings.append("No installed server Python version satisfies the project requirement.") actions.append("Align the project requirement with an installed version before redeploying.") @@ -466,8 +465,8 @@ def _incompatible_advice(is_new: bool, constraint: Optional[str], warnings: list def _unknown_advice( is_new: bool, - constraint: Optional[str], - recommended: Optional[str], + constraint: str | None, + recommended: str | None, warnings: list[str], actions: list[str], ) -> None: @@ -485,7 +484,7 @@ def _unknown_advice( actions.append("Check the project's Python metadata and server availability before publishing.") -def _local_python_version(project_dir: str, python: Optional[str]) -> str: +def _local_python_version(project_dir: str, python: str | None) -> str: interpreter = which_python(python, project_dir) if interpreter == sys.executable: return platform.python_version() @@ -504,7 +503,7 @@ def _local_python_version(project_dir: str, python: Optional[str]) -> str: def _validated_python_executor( executor: RSConnectExecutor, -) -> Tuple[Union[RSConnectServer, SPCSConnectServer], RSConnectClient]: +) -> tuple[RSConnectServer | SPCSConnectServer, RSConnectClient]: server = executor.remote_server if isinstance(server, ConnectCloudServer): raise RSConnectException( @@ -522,8 +521,8 @@ def _validated_python_executor( def _python_project_metadata( - target: str, python: Optional[str], warnings: list[str] -) -> tuple[str, str, Optional[str], Optional[str]]: + target: str, python: str | None, warnings: list[str] +) -> tuple[str, str, str | None, str | None]: target_path = Path(target) project_dir = str(target_path.parent) if target_path.is_file() else target local_python = _local_python_version(project_dir, python) @@ -537,9 +536,9 @@ def _python_project_metadata( def _status_advice( status: str, is_new: bool, - constraint: Optional[str], - invalid_metadata: Optional[str], - recommended: Optional[str], + constraint: str | None, + invalid_metadata: str | None, + recommended: str | None, warnings: list[str], actions: list[str], ) -> None: @@ -552,7 +551,7 @@ def _status_advice( def run_preflight( - executor: RSConnectExecutor, project: str, fix: bool = False, python: Optional[str] = None + executor: RSConnectExecutor, project: str, fix: bool = False, python: str | None = None ) -> dict[str, Any]: """Check project Python metadata against a validated Connect executor.""" require_posix("Deployment preflight") diff --git a/rsconnect/preflight_node.py b/rsconnect/preflight_node.py index c3eed1195..c727e7201 100644 --- a/rsconnect/preflight_node.py +++ b/rsconnect/preflight_node.py @@ -8,7 +8,8 @@ import subprocess from collections.abc import Mapping as MappingABC from pathlib import Path -from typing import Any, Dict, List, Mapping, Optional, Tuple, cast +from typing import Any, cast +from collections.abc import Mapping from .api import ConnectCloudServer, RSConnectClient, RSConnectExecutor, RSConnectServer, SPCSConnectServer from .environment_node import NodeEnvironment @@ -41,7 +42,7 @@ def _project_directory(project: str) -> str: return str(path if path.is_dir() else path.parent) -def _project_node_requirement(project: str, warnings: List[str], actions: List[str]) -> Tuple[Optional[str], bool]: +def _project_node_requirement(project: str, warnings: list[str], actions: list[str]) -> tuple[str | None, bool]: directory = Path(project) package_path = directory / "package.json" lock_path = directory / "package-lock.json" @@ -62,7 +63,7 @@ def _project_node_requirement(project: str, warnings: List[str], actions: List[s warnings.append("package.json must contain a JSON object.") actions.append("Repair package.json before deploying Node.js content.") return None, False - package = cast(Dict[str, Any], package) + package = cast(dict[str, Any], package) engines = package.get("engines") if "engines" in package and not isinstance(engines, dict): @@ -72,7 +73,7 @@ def _project_node_requirement(project: str, warnings: List[str], actions: List[s if not isinstance(engines, dict): return None, True - engines = cast(Dict[str, Any], engines) + engines = cast(dict[str, Any], engines) if "node" not in engines: return None, True requirement = engines["node"] @@ -83,7 +84,7 @@ def _project_node_requirement(project: str, warnings: List[str], actions: List[s return requirement, True -def _local_node_version(project: str, node: Optional[str], warnings: List[str], actions: List[str]) -> Optional[str]: +def _local_node_version(project: str, node: str | None, warnings: list[str], actions: list[str]) -> str | None: try: return NodeEnvironment.create(project, node_executable=node).node_version except (RSConnectException, OSError, UnicodeDecodeError) as err: @@ -105,12 +106,12 @@ def _is_npm_installation(npm_cli: Path) -> bool: return False if not isinstance(npm_metadata, dict) or not isinstance(semver_metadata, dict): return False - npm_package = cast(Dict[str, Any], npm_metadata) - semver_package = cast(Dict[str, Any], semver_metadata) + npm_package = cast(dict[str, Any], npm_metadata) + semver_package = cast(dict[str, Any], semver_metadata) return npm_package.get("name") == "npm" and semver_package.get("name") == "semver" -def _npm_cli_path() -> Optional[str]: +def _npm_cli_path() -> str | None: npm = shutil.which("npm") if not npm: return None @@ -118,28 +119,28 @@ def _npm_cli_path() -> Optional[str]: return str(npm_cli) if npm_cli.is_file() and _is_npm_installation(npm_cli) else None -def _parse_node_evaluation(stdout: str, version_count: int) -> Tuple[Optional[Dict[str, Any]], Optional[str]]: +def _parse_node_evaluation(stdout: str, version_count: int) -> tuple[dict[str, Any] | None, str | None]: try: evaluation = json.loads(stdout) except json.JSONDecodeError as err: return None, f"npm's semver evaluator returned invalid output: {err}" if not isinstance(evaluation, dict): return None, "npm's semver evaluator returned incomplete output." - evaluation = cast(Dict[str, Any], evaluation) + evaluation = cast(dict[str, Any], evaluation) if ( not isinstance(evaluation.get("range_valid"), bool) or not isinstance(evaluation.get("valid_versions"), list) or not isinstance(evaluation.get("matches"), list) ): return None, "npm's semver evaluator returned incomplete output." - valid_versions = cast(List[Any], evaluation["valid_versions"]) - matches = cast(List[Any], evaluation["matches"]) + valid_versions = cast(list[Any], evaluation["valid_versions"]) + matches = cast(list[Any], evaluation["matches"]) if not _valid_node_results(evaluation["range_valid"], valid_versions, matches, version_count): return None, "npm's semver evaluator returned incomplete version results." return evaluation, None -def _valid_node_results(range_valid: bool, valid_versions: List[Any], matches: List[Any], version_count: int) -> bool: +def _valid_node_results(range_valid: bool, valid_versions: list[Any], matches: list[Any], version_count: int) -> bool: if len(valid_versions) != version_count: return False if any(not isinstance(value, bool) for value in valid_versions + matches): @@ -150,8 +151,8 @@ def _valid_node_results(range_valid: bool, valid_versions: List[Any], matches: L def _evaluate_node_range( - node: str, requirement: Optional[str], versions: List[str] -) -> Tuple[Optional[Dict[str, Any]], Optional[str]]: + node: str, requirement: str | None, versions: list[str] +) -> tuple[dict[str, Any] | None, str | None]: npm_cli = _npm_cli_path() if npm_cli is None: return None, "Could not locate npm's local semver module." @@ -176,7 +177,7 @@ def _evaluate_node_range( return _parse_node_evaluation(result.stdout, len(versions)) -def _server_status(value: Any, warnings: List[str], actions: List[str]) -> Tuple[Optional[Dict[str, Any]], bool]: +def _server_status(value: Any, warnings: list[str], actions: list[str]) -> tuple[dict[str, Any] | None, bool]: if not isinstance(value, MappingABC): warnings.append("Connect did not return Node.js runtime status flags; compatibility is unknown.") actions.append("Check whether this Connect server exposes Node.js runtime status flags.") @@ -198,14 +199,14 @@ def _server_status(value: Any, warnings: List[str], actions: List[str]) -> Tuple return status, complete -def _server_installations(value: Any, warnings: List[str]) -> Tuple[List[Tuple[str, Optional[bool]]], bool, bool]: +def _server_installations(value: Any, warnings: list[str]) -> tuple[list[tuple[str, bool | None]], bool, bool]: if not isinstance(value, list): warnings.append("Connect did not return Node.js installations; compatibility is unknown.") return [], False, False - installations: List[Tuple[str, Optional[bool]]] = [] + installations: list[tuple[str, bool | None]] = [] metadata_complete = True publishability_complete = True - for raw_item in cast(List[Any], value): + for raw_item in cast(list[Any], value): if not isinstance(raw_item, MappingABC): metadata_complete = False publishability_complete = False @@ -227,8 +228,8 @@ def _server_installations(value: Any, warnings: List[str]) -> Tuple[List[Tuple[s return installations, metadata_complete, publishability_complete -def _server_nodejs_info(settings: Any, warnings: List[str], actions: List[str]) -> Dict[str, Any]: - info: Dict[str, Any] = { +def _server_nodejs_info(settings: Any, warnings: list[str], actions: list[str]) -> dict[str, Any]: + info: dict[str, Any] = { "enabled": None, "status": None, "installations": [], @@ -259,7 +260,7 @@ def _server_nodejs_info(settings: Any, warnings: List[str], actions: List[str]) return info -def _nodejs_status_failures(info: Dict[str, Any]) -> List[str]: +def _nodejs_status_failures(info: dict[str, Any]) -> list[str]: status = info["status"] if not isinstance(status, MappingABC): return [] @@ -267,29 +268,29 @@ def _nodejs_status_failures(info: Dict[str, Any]) -> List[str]: return [field for field in _NODEJS_STATUS_FLAGS if status.get(field) is False] -def _eligible_installations(installations: List[Tuple[str, Optional[bool]]], is_new: bool) -> List[int]: +def _eligible_installations(installations: list[tuple[str, bool | None]], is_new: bool) -> list[int]: return [index for index, (_, publishable) in enumerate(installations) if not is_new or publishable is True] -def _valid_node_evaluation(evaluation: Optional[Dict[str, Any]]) -> bool: +def _valid_node_evaluation(evaluation: dict[str, Any] | None) -> bool: return evaluation is not None and evaluation["range_valid"] -def _has_matching_installation(indices: List[int], evaluation: Dict[str, Any]) -> bool: +def _has_matching_installation(indices: list[int], evaluation: dict[str, Any]) -> bool: valid_versions = evaluation["valid_versions"] matches = evaluation["matches"] return any(valid_versions[index] and matches[index] for index in indices) def _unmatched_server_compatibility( - indices: List[int], is_new: bool, info: Dict[str, Any], evaluation: Dict[str, Any] + indices: list[int], is_new: bool, info: dict[str, Any], evaluation: dict[str, Any] ) -> str: versions_complete = all(evaluation["valid_versions"][index] for index in indices) flags_complete = info["publishability_complete"] or not is_new return "incompatible" if versions_complete and flags_complete else "unknown" -def _server_compatibility(info: Dict[str, Any], is_new: bool, evaluation: Optional[Dict[str, Any]]) -> str: +def _server_compatibility(info: dict[str, Any], is_new: bool, evaluation: dict[str, Any] | None) -> str: if info["enabled"] is False or _nodejs_status_failures(info): return "incompatible" if not info["runtime_complete"]: @@ -302,14 +303,14 @@ def _server_compatibility(info: Dict[str, Any], is_new: bool, evaluation: Option return "incompatible" if flags_complete else "unknown" if not _valid_node_evaluation(evaluation): return "unknown" - if _has_matching_installation(indices, cast(Dict[str, Any], evaluation)): + if _has_matching_installation(indices, cast(dict[str, Any], evaluation)): return "compatible" if info["status_complete"] else "unknown" - return _unmatched_server_compatibility(indices, is_new, info, cast(Dict[str, Any], evaluation)) + return _unmatched_server_compatibility(indices, is_new, info, cast(dict[str, Any], evaluation)) def _existing_content_version( - client: RSConnectClient, app_id: str, warnings: List[str], actions: List[str] -) -> Tuple[Optional[str], bool]: + client: RSConnectClient, app_id: str, warnings: list[str], actions: list[str] +) -> tuple[str | None, bool]: try: content = client.content_get(app_id) except RSConnectException as err: @@ -330,12 +331,12 @@ def _existing_content_version( def _existing_content( client: RSConnectClient, exists: bool, - app_id: Optional[str], + app_id: str | None, compatibility: str, - warnings: List[str], - actions: List[str], - target_issue: Optional[str], -) -> Tuple[Dict[str, Any], bool]: + warnings: list[str], + actions: list[str], + target_issue: str | None, +) -> tuple[dict[str, Any], bool]: node_version = None readable = not exists if exists and app_id: @@ -351,7 +352,7 @@ def _existing_content( }, readable -def _validated_executor(executor: RSConnectExecutor) -> Tuple[Any, RSConnectClient]: +def _validated_executor(executor: RSConnectExecutor) -> tuple[Any, RSConnectClient]: server = executor.remote_server if isinstance(server, ConnectCloudServer) or not isinstance(server, (RSConnectServer, SPCSConnectServer)): raise RSConnectException("Node.js preflight supports self-hosted Posit Connect and Connect in SPCS.") @@ -363,7 +364,7 @@ def _validated_executor(executor: RSConnectExecutor) -> Tuple[Any, RSConnectClie return server, client -def _read_server_nodejs_info(client: RSConnectClient, warnings: List[str], actions: List[str]) -> Dict[str, Any]: +def _read_server_nodejs_info(client: RSConnectClient, warnings: list[str], actions: list[str]) -> dict[str, Any]: try: settings = client.nodejs_settings() except RSConnectException as err: @@ -374,12 +375,12 @@ def _read_server_nodejs_info(client: RSConnectClient, warnings: List[str], actio def _evaluate_project_range( node: str, - requirement: Optional[str], - versions: List[str], + requirement: str | None, + versions: list[str], project_metadata_valid: bool, - warnings: List[str], - actions: List[str], -) -> Tuple[Optional[Dict[str, Any]], Optional[str]]: + warnings: list[str], + actions: list[str], +) -> tuple[dict[str, Any] | None, str | None]: if not project_metadata_valid: return None, None evaluation, error = _evaluate_node_range(node, requirement, versions) @@ -393,8 +394,8 @@ def _evaluate_project_range( def _project_details( - project: str, node: Optional[str], warnings: List[str], actions: List[str] -) -> Tuple[str, Optional[str], bool, Optional[str]]: + project: str, node: str | None, warnings: list[str], actions: list[str] +) -> tuple[str, str | None, bool, str | None]: directory = _project_directory(project) requirement, metadata_valid = _project_node_requirement(directory, warnings, actions) local_node = _local_node_version(directory, node, warnings, actions) if metadata_valid else None @@ -403,9 +404,9 @@ def _project_details( def _local_checks_complete( metadata_valid: bool, - local_node: Optional[str], - evaluation: Optional[Dict[str, Any]], - evaluation_error: Optional[str], + local_node: str | None, + evaluation: dict[str, Any] | None, + evaluation_error: str | None, ) -> bool: return ( metadata_valid @@ -416,7 +417,7 @@ def _local_checks_complete( ) -def _add_status_failure_actions(info: Dict[str, Any], actions: List[str]) -> List[str]: +def _add_status_failure_actions(info: dict[str, Any], actions: list[str]) -> list[str]: failures = _nodejs_status_failures(info) if info["enabled"] is False: actions.append("Enable Node.js on the Connect server before publishing.") @@ -432,11 +433,11 @@ def _add_status_failure_actions(info: Dict[str, Any], actions: List[str]) -> Lis def _add_server_advice( - info: Dict[str, Any], + info: dict[str, Any], compatibility: str, exists: bool, - warnings: List[str], - actions: List[str], + warnings: list[str], + actions: list[str], ) -> None: failures = _add_status_failure_actions(info, actions) if info["enabled"] is False or failures or compatibility != "incompatible": @@ -451,7 +452,7 @@ def _add_server_advice( def _reported_status( compatibility: str, - enabled: Optional[bool], + enabled: bool | None, local_checks_complete: bool, target_resolved: bool, content_readable: bool, @@ -465,12 +466,12 @@ def _reported_status( return "ok" if compatibility == "compatible" else compatibility -def run_node_preflight(executor: RSConnectExecutor, project: str, node: Optional[str] = None) -> Dict[str, Any]: +def run_node_preflight(executor: RSConnectExecutor, project: str, node: str | None = None) -> dict[str, Any]: """Check Node.js project metadata against a validated Connect executor.""" require_posix("Deployment preflight") server, client = _validated_executor(executor) - warnings: List[str] = [] - actions: List[str] = [] + warnings: list[str] = [] + actions: list[str] = [] target = project _, requirement, project_metadata_valid, local_node = _project_details(project, node, warnings, actions) info = _read_server_nodejs_info(client, warnings, actions) diff --git a/rsconnect/pyproject.py b/rsconnect/pyproject.py index 5ce24f425..407908939 100644 --- a/rsconnect/pyproject.py +++ b/rsconnect/pyproject.py @@ -23,7 +23,7 @@ VALID_VERSION_REQ_REGEX = rf"^({PEP440_OPERATORS_REGEX}?\d+(\.[\d\*]+)*)+$" -def local_python_mismatch(constraint: typing.Optional[str], version: str) -> typing.Optional[str]: +def local_python_mismatch(constraint: str | None, version: str) -> str | None: if constraint is None: return None try: @@ -37,7 +37,7 @@ def local_python_mismatch(constraint: typing.Optional[str], version: str) -> typ ) -def detect_python_version_requirement(directory: typing.Union[str, pathlib.Path]) -> typing.Optional[str]: +def detect_python_version_requirement(directory: str | pathlib.Path) -> str | None: """Detect the python version requirement for a project. The directory should contain a metadata file such as pyproject.toml, @@ -59,7 +59,7 @@ def detect_python_version_requirement(directory: typing.Union[str, pathlib.Path] return None -def lookup_metadata_file(directory: typing.Union[str, pathlib.Path]) -> typing.List[typing.Tuple[str, pathlib.Path]]: +def lookup_metadata_file(directory: str | pathlib.Path) -> list[tuple[str, pathlib.Path]]: """Given the directory of a project return the path of a usable metadata file. The returned value is either a list of tuples [(filename, path)] or @@ -81,7 +81,7 @@ def _generate(): def get_python_version_requirement_parser( metadata_file: pathlib.Path, -) -> typing.Callable[[pathlib.Path], typing.Optional[str]]: +) -> typing.Callable[[pathlib.Path], str | None]: """Given the metadata file, return the appropriate parser function. The returned function takes a pathlib.Path and returns the parsed value. @@ -96,7 +96,7 @@ def get_python_version_requirement_parser( raise NotImplementedError(f"Unknown metadata file type: {metadata_file.name}") -def parse_pyproject_python_requires(pyproject_file: pathlib.Path) -> typing.Optional[str]: +def parse_pyproject_python_requires(pyproject_file: pathlib.Path) -> str | None: """Parse the project.requires-python field from a pyproject.toml file. Assumes that the pyproject.toml file exists, is accessible and well formatted. @@ -109,7 +109,7 @@ def parse_pyproject_python_requires(pyproject_file: pathlib.Path) -> typing.Opti return pyproject.get("project", {}).get("requires-python", None) -def parse_setupcfg_python_requires(setupcfg_file: pathlib.Path) -> typing.Optional[str]: +def parse_setupcfg_python_requires(setupcfg_file: pathlib.Path) -> str | None: """Parse the options.python_requires field from a setup.cfg file. Assumes that the setup.cfg file exists, is accessible and well formatted. @@ -122,7 +122,7 @@ def parse_setupcfg_python_requires(setupcfg_file: pathlib.Path) -> typing.Option return config.get("options", "python_requires", fallback=None) -def parse_pyversion_python_requires(pyversion_file: pathlib.Path) -> typing.Optional[str]: +def parse_pyversion_python_requires(pyversion_file: pathlib.Path) -> str | None: """Parse the python version from a .python-version file. Assumes that the .python-version file exists, is accessible and well formatted. @@ -144,7 +144,7 @@ def adapt_python_requires( """ current_contraints = python_requires.split(",") - def _adapt_contraint(constraints: typing.List[str]) -> typing.Generator[str, None, None]: + def _adapt_contraint(constraints: list[str]) -> typing.Generator[str, None, None]: for constraint in constraints: constraint = constraint.strip() if "@" in constraint or "-" in constraint or "/" in constraint: @@ -209,7 +209,7 @@ def read_tool_rsconnect(pyproject_file: pathlib.Path) -> typing.Mapping[str, typ return _read_deployment_config(pyproject_file)[1] -def _read_deployment_config(pyproject_file: pathlib.Path) -> typing.Tuple[str, typing.Mapping[str, typing.Any]]: +def _read_deployment_config(pyproject_file: pathlib.Path) -> tuple[str, typing.Mapping[str, typing.Any]]: content = pyproject_file.read_text(encoding="utf-8-sig") pyproject = tomllib.loads(content) tool = pyproject.get("tool") @@ -263,13 +263,13 @@ class PyprojectDeployTarget: configured_app_mode: str entrypoint: str requirements_file: str - title: typing.Optional[str] + title: str | None def resolve_pyproject_deploy_target( pyproject_file: pathlib.Path, - requirements_file: typing.Optional[str] = None, - title_override: typing.Optional[str] = None, + requirements_file: str | None = None, + title_override: str | None = None, ) -> PyprojectDeployTarget: """Resolve the deployment target described in pyproject.toml. @@ -305,5 +305,5 @@ def resolve_pyproject_deploy_target( configured_app_mode=configured_app_mode, entrypoint=typing.cast(str, config["entrypoint"]), requirements_file=typing.cast(str, requirements_file or config.get("requirements_file") or "pyproject.toml"), - title=typing.cast(typing.Optional[str], config.get("title")) or title_override, + title=typing.cast(str | None, config.get("title")) or title_override, ) diff --git a/rsconnect/quickstart/quickstart.py b/rsconnect/quickstart/quickstart.py index f1f606c8d..4efe80774 100644 --- a/rsconnect/quickstart/quickstart.py +++ b/rsconnect/quickstart/quickstart.py @@ -49,9 +49,9 @@ def run_quickstart( app_type: str, name: str, *, - python_version: typing.Optional[str] = None, - server_python_settings: typing.Optional[typing.Callable[[], typing.Optional[typing.Tuple[object, str]]]] = None, - cwd: typing.Optional[pathlib.Path] = None, + python_version: str | None = None, + server_python_settings: typing.Callable[[], tuple[object, str] | None] | None = None, + cwd: pathlib.Path | None = None, ) -> pathlib.Path: """Scaffold a new Connect project of ``app_type`` named ``name``. @@ -94,7 +94,7 @@ def run_quickstart( # verbatim. A bare version is padded to at most three segments so the # ``.*`` wildcard appears only when a patch level is omitted: ``3.10`` -> # ``==3.10.*`` (any 3.10.x), ``3.11.14`` -> ``==3.11.14`` (exact). - venv_python: typing.Optional[str] = None + venv_python: str | None = None if python_version is None: requires_python = _REQUIRES_PYTHON venv_python = sys.executable @@ -142,7 +142,7 @@ def _newest_publishable_python(settings: object) -> str: ) versions: list[tuple[int, ...]] = [] if isinstance(installations, list): - for item in typing.cast(typing.List[object], installations): + for item in typing.cast(list[object], installations): if not isinstance(item, dict): continue installation = typing.cast(typing.Mapping[str, object], item) @@ -271,9 +271,9 @@ class TemplateSpec: pyproject_template: str readme_template: str - local_run_command: typing.Tuple[str, ...] - source_files: typing.Tuple[FileSpec, ...] - notes: typing.Tuple[str, ...] = () + local_run_command: tuple[str, ...] + source_files: tuple[FileSpec, ...] + notes: tuple[str, ...] = () # Registry key: the canonical :class:`AppMode` singleton. The CLI alias @@ -349,7 +349,7 @@ class TemplateSpec: } -def _supported_aliases() -> typing.Tuple[str, ...]: +def _supported_aliases() -> tuple[str, ...]: """CLI aliases whose :class:`AppMode` has a quickstart template. Derived from :data:`AppModes._cli_aliases` and :data:`_REGISTRY`: an @@ -470,7 +470,7 @@ def _format_local_run(spec: TemplateSpec, *, name: str) -> str: # --------------------------------------------------------------------------- -def _install_venv(target: pathlib.Path, python: typing.Optional[str] = None) -> None: +def _install_venv(target: pathlib.Path, python: str | None = None) -> None: """Populate ``.venv/`` via ``uv venv`` + ``uv sync``. ``python`` is passed to ``uv venv --python``; when omitted, uv chooses an diff --git a/rsconnect/snowflake.py b/rsconnect/snowflake.py index 8fbf9d7db..c08896644 100644 --- a/rsconnect/snowflake.py +++ b/rsconnect/snowflake.py @@ -3,7 +3,7 @@ import json from subprocess import CalledProcessError, CompletedProcess, run -from typing import Any, Dict, List, Optional +from typing import Any from .exception import RSConnectException from .log import logger @@ -30,7 +30,7 @@ def ensure_snow_installed() -> None: raise RSConnectException("snow cannot be found.") -def list_connections() -> List[Dict[str, Any]]: +def list_connections() -> list[dict[str, Any]]: try: res = snow("connection", "list", "--format", "json") @@ -40,7 +40,7 @@ def list_connections() -> List[Dict[str, Any]]: raise RSConnectException("Could not list snowflake connections.") -def get_parameters(name: Optional[str] = None) -> Dict[str, Any]: +def get_parameters(name: str | None = None) -> dict[str, Any]: """Get Snowflake connection parameters. Args: name: The name of the connection to retrieve. If None, returns the default connection. @@ -74,7 +74,7 @@ def get_parameters(name: Optional[str] = None) -> Dict[str, Any]: raise RSConnectException(f"Could not get Snowflake connection: {e}") -def generate_jwt(name: Optional[str] = None) -> str: +def generate_jwt(name: str | None = None) -> str: _ = get_parameters(name) connection_name = "" if name is None else name diff --git a/rsconnect/subprocesses/inspect_environment.py b/rsconnect/subprocesses/inspect_environment.py index fb7d8ed7a..c3a1685a5 100644 --- a/rsconnect/subprocesses/inspect_environment.py +++ b/rsconnect/subprocesses/inspect_environment.py @@ -22,7 +22,8 @@ import subprocess import sys from dataclasses import asdict, dataclass, replace -from typing import Any, Callable, List, Optional, cast +from typing import Any, cast +from collections.abc import Callable from urllib.parse import parse_qs, quote, urlsplit from urllib.request import url2pathname @@ -42,11 +43,11 @@ class EnvironmentData: filename: str locale: str package_manager: str - pip: Optional[str] + pip: str | None python: str source: str - python_requires: Optional[str] - error: Optional[str] + python_requires: str | None + error: str | None def _asdict(self): return asdict(self) @@ -60,11 +61,11 @@ def MakeEnvironmentData( filename: str, locale: str, package_manager: str, - pip: Optional[str], + pip: str | None, python: str, source: str, - python_requires: Optional[str] = None, - error: Optional[str] = None, + python_requires: str | None = None, + error: str | None = None, **kwargs: object, # provides compatibility where we no longer support some older properties ) -> EnvironmentData: return EnvironmentData(contents, filename, locale, package_manager, pip, python, source, python_requires, error) @@ -76,7 +77,7 @@ class EnvironmentException(Exception): def detect_environment( dirname: str, - requirements_file: Optional[str] = "requirements.txt", + requirements_file: str | None = "requirements.txt", uv_path: str = "uv", python: str = sys.executable, ) -> EnvironmentData: @@ -134,7 +135,7 @@ def get_default_locale(locale_source: Callable[..., tuple[str | None, str | None return "" if result == "." else result -def get_version(module: str, python: str = sys.executable) -> Optional[str]: +def get_version(module: str, python: str = sys.executable) -> str | None: try: args = [python, "-E", "-m", module, "--version"] proc = subprocess.Popen( @@ -173,7 +174,7 @@ def output_file(dirname: str, filename: str, package_manager: str): return None # Keep CRLF line endings. Text mode changes them to LF. - with open(path, "r", newline="") as f: + with open(path, newline="") as f: data = f.read() data = "\n".join(line for line in data.split("\n") if not is_rsconnect_requirement(line)) @@ -188,7 +189,7 @@ def output_file(dirname: str, filename: str, package_manager: str): raise EnvironmentException("Error reading %s: %s" % (filename, str(exception))) -def pip_freeze(python: str, uv_path: str, pip_version: Optional[str], python_version: str): +def pip_freeze(python: str, uv_path: str, pip_version: str | None, python_version: str): """Inspect the environment using `pip freeze`. Returns a dictionary containing the filename @@ -243,7 +244,7 @@ def pip_freeze(python: str, uv_path: str, pip_version: Optional[str], python_ver pip_stdout = ( "# requirements.txt generated by rsconnect-python on " - + str(datetime.datetime.now(datetime.timezone.utc)) + + str(datetime.datetime.now(datetime.UTC)) + "\n" + pip_stdout ) @@ -299,13 +300,13 @@ def uv_export(dirname: str, lock_filename: str, uv_path: str = "uv"): if result.returncode != 0: raise EnvironmentException("Error during uv export: exited with code %d" % result.returncode) - with open(output_path, mode="r", encoding="utf-8") as output_file: + with open(output_path, encoding="utf-8") as output_file: exported = output_file.read() requirements = filter_pip_freeze_output(exported) requirements = ( "# requirements.txt.lock generated from uv.lock by rsconnect-python on " - + str(datetime.datetime.now(datetime.timezone.utc)) + + str(datetime.datetime.now(datetime.UTC)) + "\n" + requirements ) @@ -335,7 +336,7 @@ def pyproject_dependencies(dirname: str, pyproject_filename: str): raise EnvironmentException(f"pyproject.toml not found: {pyproject_filename}") try: - with open(pyproject_path, "r", encoding="utf-8-sig") as f: + with open(pyproject_path, encoding="utf-8-sig") as f: project_data = tomllib.loads(f.read()).get("project", {}) except Exception as exception: raise EnvironmentException(f"Error reading {pyproject_filename}: {exception}") @@ -345,12 +346,12 @@ def pyproject_dependencies(dirname: str, pyproject_filename: str): if not isinstance(dependencies, list) or not all(isinstance(dep, str) for dep in dependencies): raise EnvironmentException(f"Invalid project.dependencies in {pyproject_filename}: expected a list of strings.") - requirements = filter_pip_freeze_output("\n".join(cast(List[str], dependencies))) + requirements = filter_pip_freeze_output("\n".join(cast(list[str], dependencies))) if requirements and not requirements.endswith("\n"): requirements += "\n" requirements = ( f"# requirements.txt generated from pyproject.toml by rsconnect-python on " - f"{datetime.datetime.now(datetime.timezone.utc)}\n" + f"{datetime.datetime.now(datetime.UTC)}\n" f"{requirements}" ) @@ -415,7 +416,7 @@ def is_rsconnect_requirement(line: str) -> bool: return canonicalize_name(requirement.name) in excluded_distributions -def editable_target(line: str) -> Optional[str]: +def editable_target(line: str) -> str | None: line = re.split(r"\s+#", line.strip(), maxsplit=1)[0].rstrip() if line.startswith("--editable="): return line[len("--editable=") :].strip() @@ -445,7 +446,7 @@ def is_unbundleable_editable(line: str, dirname: str) -> bool: return urlsplit(target).scheme.lower().endswith("+file") -def bundleable_editable_path(target: str, dirname: str) -> Optional[str]: +def bundleable_editable_path(target: str, dirname: str) -> str | None: if not is_path(target): url = urlsplit(target) if url.scheme.lower() != "file" or url.netloc not in ("", "localhost") or url.query or url.fragment: diff --git a/rsconnect/timeouts.py b/rsconnect/timeouts.py index 6491860a2..6f530e567 100644 --- a/rsconnect/timeouts.py +++ b/rsconnect/timeouts.py @@ -1,7 +1,6 @@ import os import textwrap -from typing import Union from rsconnect.exception import RSConnectException @@ -29,7 +28,7 @@ def get_request_timeout() -> int: :raises: `RSConnectException` if CONNECT_REQUEST_TIMEOUT is not a natural number. :return: the timeout value """ - timeout: Union[int, str] = os.environ.get(_CONNECT_REQUEST_TIMEOUT_KEY, _CONNECT_REQUEST_TIMEOUT_DEFAULT_VALUE) + timeout: int | str = os.environ.get(_CONNECT_REQUEST_TIMEOUT_KEY, _CONNECT_REQUEST_TIMEOUT_DEFAULT_VALUE) try: timeout = int(timeout) @@ -61,7 +60,7 @@ def get_task_timeout() -> int: :raises: `RSConnectException` if CONNECT_TASK_TIMEOUT is not a positive integer. :return: the timeout value """ - timeout: Union[int, str] = os.environ.get(_CONNECT_TASK_TIMEOUT_KEY, _CONNECT_TASK_TIMEOUT_DEFAULT_VALUE) + timeout: int | str = os.environ.get(_CONNECT_TASK_TIMEOUT_KEY, _CONNECT_TASK_TIMEOUT_DEFAULT_VALUE) try: timeout = int(timeout) diff --git a/rsconnect/validation.py b/rsconnect/validation.py index f8689789c..9ac72dd53 100644 --- a/rsconnect/validation.py +++ b/rsconnect/validation.py @@ -1,7 +1,7 @@ from __future__ import annotations import os -from typing import Any, Optional +from typing import Any import click @@ -16,7 +16,7 @@ def require_posix(feature: str) -> None: def get_parameter_source_name_from_ctx( var_or_param_name: str, - ctx: Optional[click.Context], + ctx: click.Context | None, ) -> str: if ctx: varName = var_or_param_name.replace("-", "_") @@ -26,7 +26,7 @@ def get_parameter_source_name_from_ctx( return "" -def effective_connect_cloud_account(ctx: Optional[click.Context], account_name: Optional[str]) -> Optional[str]: +def effective_connect_cloud_account(ctx: click.Context | None, account_name: str | None) -> str | None: """The -A value to use when the target is Posit Connect Cloud. -A/--account is shared with shinyapps.io, whose environment variable is @@ -41,8 +41,8 @@ def effective_connect_cloud_account(ctx: Optional[click.Context], account_name: def _get_present_options( - options: dict[str, Optional[Any]], - ctx: Optional[click.Context], + options: dict[str, Any | None], + ctx: click.Context | None, ignore_sources: tuple[str, ...] = (), ) -> list[str]: """The options that have a value, labelled with where each came from. @@ -79,7 +79,7 @@ def _get_present_options( } -def typed_connect_only_deploy_options(ctx: Optional[click.Context]) -> list[str]: +def typed_connect_only_deploy_options(ctx: click.Context | None) -> list[str]: """The Connect-only deploy options this command line passed. Judged by parameter source rather than by value: --disable-env-management-py @@ -100,12 +100,12 @@ def typed_connect_only_deploy_options(ctx: Optional[click.Context]) -> list[str] def _reject_options_the_target_has_no_use_for( - ctx: Optional[click.Context], + ctx: click.Context | None, target: str, - api_key: Optional[str], + api_key: str | None, insecure: bool, - cacert: Optional[str], - snowflake_connection_name: Optional[str], + cacert: str | None, + snowflake_connection_name: str | None, reject_connect_only_deploy_options: bool, ): """Reject typed Posit Connect and SPCS options for another target. @@ -144,11 +144,11 @@ def _reject_options_the_target_has_no_use_for( def validate_connect_cloud_incompatible_options( - ctx: Optional[click.Context], - api_key: Optional[str], + ctx: click.Context | None, + api_key: str | None, insecure: bool, - cacert: Optional[str], - snowflake_connection_name: Optional[str], + cacert: str | None, + snowflake_connection_name: str | None, ): """Reject options that have no meaning on Posit Connect Cloud. @@ -167,11 +167,11 @@ def validate_connect_cloud_incompatible_options( def validate_shinyapps_incompatible_options( - ctx: Optional[click.Context], - api_key: Optional[str], + ctx: click.Context | None, + api_key: str | None, insecure: bool, - cacert: Optional[str], - snowflake_connection_name: Optional[str], + cacert: str | None, + snowflake_connection_name: str | None, ): """Reject options that have no meaning on shinyapps.io. @@ -191,9 +191,9 @@ def validate_shinyapps_incompatible_options( def validate_connect_cloud_credential_options( - ctx: Optional[click.Context], - client_id: Optional[str], - client_secret: Optional[str], + ctx: click.Context | None, + client_id: str | None, + client_secret: str | None, ): """Reject typed Connect Cloud credentials when the target is not Connect Cloud. @@ -215,19 +215,19 @@ def validate_connect_cloud_credential_options( def validate_connection_options( - ctx: Optional[click.Context], - url: Optional[str], - api_key: Optional[str], + ctx: click.Context | None, + url: str | None, + api_key: str | None, insecure: bool, - cacert: Optional[str], - account_name: Optional[str], - token: Optional[str], - secret: Optional[str], - name: Optional[str] = None, - snowflake_connection_name: Optional[str] = None, + cacert: str | None, + account_name: str | None, + token: str | None, + secret: str | None, + name: str | None = None, + snowflake_connection_name: str | None = None, has_default_server: bool = False, - client_id: Optional[str] = None, - client_secret: Optional[str] = None, + client_id: str | None = None, + client_secret: str | None = None, connect_cloud: bool = False, has_saved_connect_cloud_account: bool = False, ): @@ -427,7 +427,7 @@ def validate_connection_options( class PythonVersionParamType(click.ParamType): name = "python-version" - def convert(self, value: str, param: Optional[click.Parameter], ctx: Optional[click.Context]): + def convert(self, value: str, param: click.Parameter | None, ctx: click.Context | None): try: parts = list(map(int, value.split("."))) if len(parts) in (2, 3): diff --git a/rsconnect/version_check.py b/rsconnect/version_check.py index a47225165..85d70dc4a 100644 --- a/rsconnect/version_check.py +++ b/rsconnect/version_check.py @@ -18,7 +18,7 @@ import time from http.client import HTTPSConnection from os.path import join -from typing import NamedTuple, Optional, Tuple +from typing import NamedTuple from packaging.specifiers import InvalidSpecifier, SpecifierSet from packaging.version import Version @@ -36,7 +36,7 @@ class _Release(NamedTuple): version: str - requires_python: Optional[str] + requires_python: str | None def _is_check_disabled() -> bool: @@ -55,7 +55,7 @@ def _cache_path() -> str: return join(config_dirname(), _CACHE_FILENAME) -def _read_cache() -> Tuple[bool, Optional[_Release]]: +def _read_cache() -> tuple[bool, _Release | None]: """Return freshness and the cached release, retaining stale data for the hint.""" try: with open(_cache_path()) as f: @@ -73,7 +73,7 @@ def _read_cache() -> Tuple[bool, Optional[_Release]]: return (False, None) -def _write_cache(release: Optional[_Release]) -> None: +def _write_cache(release: _Release | None) -> None: """Cache failures too, so they do not trigger another request until the TTL expires.""" try: path = _cache_path() @@ -91,7 +91,7 @@ def _write_cache(release: Optional[_Release]) -> None: pass -def _fetch_latest_version() -> Optional[_Release]: +def _fetch_latest_version() -> _Release | None: conn = None try: conn = HTTPSConnection(_PYPI_HOST, timeout=_PYPI_TIMEOUT_SECONDS) @@ -112,7 +112,7 @@ def _fetch_latest_version() -> Optional[_Release]: conn.close() -def _update_message(release: Optional[_Release]) -> Optional[str]: +def _update_message(release: _Release | None) -> str | None: """Return an upgrade warning if the release is newer than the running version.""" try: if release is None or Version(release.version) <= Version(VERSION): @@ -144,8 +144,8 @@ class BackgroundVersionCheck: """Resolves the latest available version, using a cache and a background fetch.""" def __init__(self) -> None: - self._thread: Optional[threading.Thread] = None - self._release: Optional[_Release] = None + self._thread: threading.Thread | None = None + self._release: _Release | None = None def start(self) -> None: if _is_check_disabled() or _is_dev_version(VERSION): @@ -162,7 +162,7 @@ def _run(self) -> None: if release is not None: self._release = release - def get_warning_message(self) -> Optional[str]: + def get_warning_message(self) -> str | None: # Only a cold cache waits briefly for the background fetch. if self._release is None and self._thread is not None: self._thread.join(timeout=_PYPI_TIMEOUT_SECONDS) diff --git a/tests/_local_run.py b/tests/_local_run.py index 3acd3face..246a3b11b 100644 --- a/tests/_local_run.py +++ b/tests/_local_run.py @@ -27,7 +27,7 @@ import urllib.error import urllib.request from pathlib import Path -from typing import Iterator, Mapping, Optional, Sequence, Tuple +from collections.abc import Iterator, Mapping, Sequence def find_free_port() -> int: @@ -50,7 +50,7 @@ def spawn( cmd: Sequence[str], *, cwd: Path, - extra_env: Optional[Mapping[str, str]] = None, + extra_env: Mapping[str, str] | None = None, ) -> Iterator[subprocess.Popen]: """Run ``uv run `` in ``cwd`` and tear down the whole process group on exit. @@ -108,7 +108,7 @@ def spawn( def wait_for_http( port: int, *, - proc: Optional[subprocess.Popen] = None, + proc: subprocess.Popen | None = None, timeout: float = 60.0, ) -> None: """Poll ``http://127.0.0.1:/`` until any non-5xx response arrives. @@ -125,7 +125,7 @@ def wait_for_http( the liveness check still requires our child to be running. """ deadline = time.monotonic() + timeout - last_error: Optional[BaseException] = None + last_error: BaseException | None = None url = f"http://127.0.0.1:{port}/" while time.monotonic() < deadline: if proc is not None and proc.poll() is not None: @@ -171,7 +171,7 @@ def wait_for_artifact( assert artifact.stat().st_size > 0, f"expected artifact empty: {artifact}" -def http_command(app_type: str, port: int) -> Tuple[Sequence[str], Mapping[str, str]]: +def http_command(app_type: str, port: int) -> tuple[Sequence[str], Mapping[str, str]]: """Return the argv tail and env overrides that boot ``app_type`` on ``port``. Different frameworks accept their bind port through different channels: @@ -192,7 +192,7 @@ def http_command(app_type: str, port: int) -> Tuple[Sequence[str], Mapping[str, raise ValueError(f"no http command for app_type={app_type!r}") -def artifact_command(app_type: str) -> Tuple[str, ...]: +def artifact_command(app_type: str) -> tuple[str, ...]: """Return the argv tail (after ``uv run``) that renders ``app_type`` to disk.""" if app_type == "notebook": # ``--to notebook`` is required by recent nbconvert versions and yields diff --git a/tests/conftest.py b/tests/conftest.py index b85d8e6fb..5d1161480 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,5 @@ import sys -from typing import Iterator +from collections.abc import Iterator from unittest import mock import pytest diff --git a/tests/target_helpers.py b/tests/target_helpers.py index f3fcd8174..f888f2686 100644 --- a/tests/target_helpers.py +++ b/tests/target_helpers.py @@ -13,7 +13,7 @@ import os import pathlib import tempfile -from typing import Any, Dict, Optional +from typing import Any from unittest import mock import click @@ -47,9 +47,9 @@ def _ctx(**sources: ParameterSource) -> click.Context: return ctx -def _deploy_option_flags() -> Dict[str, set[frozenset[str]]]: +def _deploy_option_flags() -> dict[str, set[frozenset[str]]]: """The flags each `deploy` subcommand option is spelled with, by parameter name.""" - flags: Dict[str, set[frozenset[str]]] = {} + flags: dict[str, set[frozenset[str]]] = {} for command in cli.commands["deploy"].commands.values(): for param in command.params: if isinstance(param, click.Option) and param.name: @@ -128,12 +128,12 @@ def _store_with_cloud_entry(**fields: Any) -> ServerStore: def _setup_remote_server( - ctx: Optional[click.Context] = None, - store: Optional[ServerStore] = None, - resolve: Optional[ServerData] = None, - default: Optional[ServerData] = None, - has_cloud_account: Optional[bool] = None, - environ: Optional[Dict[str, str]] = None, + ctx: click.Context | None = None, + store: ServerStore | None = None, + resolve: ServerData | None = None, + default: ServerData | None = None, + has_cloud_account: bool | None = None, + environ: dict[str, str] | None = None, **kwargs: Any, ) -> RSConnectExecutor: """Run setup_remote_server on a bare executor with the store interactions mocked. diff --git a/tests/test_bundle.py b/tests/test_bundle.py index 44fa6d1ed..13e406f29 100644 --- a/tests/test_bundle.py +++ b/tests/test_bundle.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import builtins import io import json diff --git a/tests/test_conftest.py b/tests/test_conftest.py index 1dfde8741..1e701aaba 100644 --- a/tests/test_conftest.py +++ b/tests/test_conftest.py @@ -1,7 +1,7 @@ import contextlib import sys import types -from typing import Generator, Iterator +from collections.abc import Generator, Iterator import pytest diff --git a/tests/test_connect_cloud.py b/tests/test_connect_cloud.py index 8d140621c..dbb4bbd3a 100644 --- a/tests/test_connect_cloud.py +++ b/tests/test_connect_cloud.py @@ -8,7 +8,7 @@ import tarfile import tempfile import unittest -from typing import Any, Dict, Optional +from typing import Any from unittest import mock import click @@ -380,9 +380,9 @@ def _json_body(request): return json.loads(request.body.decode("utf-8")) -def _validate_options(ctx: Optional[click.Context] = None, **overrides: Any) -> None: +def _validate_options(ctx: click.Context | None = None, **overrides: Any) -> None: """validate_connection_options with --connect-cloud set and everything else absent.""" - options: Dict[str, Any] = dict( + options: dict[str, Any] = dict( url=None, api_key=None, insecure=False, @@ -419,12 +419,12 @@ class PasswordDeleteError(Exception): pass def __init__(self): - self.passwords: Dict[Any, str] = {} + self.passwords: dict[Any, str] = {} def set_password(self, service: str, username: str, password: str) -> None: self.passwords[(service, username)] = password - def get_password(self, service: str, username: str) -> Optional[str]: + def get_password(self, service: str, username: str) -> str | None: return self.passwords.get((service, username)) def delete_password(self, service: str, username: str) -> None: @@ -1084,7 +1084,7 @@ class TestConnectCloudStreamBodyRetry(unittest.TestCase): """The retry-once skeleton is shared with the Posit Connect client, so a streamed body is rewound before the retry here too rather than arriving empty.""" - def _attempt_bodies(self, body: Any, server: Optional[ConnectCloudServer] = None, read: bool = True) -> list[Any]: + def _attempt_bodies(self, body: Any, server: ConnectCloudServer | None = None, read: bool = True) -> list[Any]: """The body each attempt was given, read out when `read`, with refresh stubbed.""" client = ConnectCloudClient(server or ConnectCloudServer("acme", access_token="stale", refresh_token="rt")) seen: list[Any] = [] @@ -3039,7 +3039,7 @@ def _record(self, server_url: str, app_id: str = "42", app_mode: Any = AppModes. store = self._store() store.set(server_url, self.app_dir, "https://acme.shinyapps.io/my-app", app_id, None, "My App", app_mode) - def _executor(self, account_name: str = "acme", account_id: Optional[str] = "acct-1") -> RSConnectExecutor: + def _executor(self, account_name: str = "acme", account_id: str | None = "acct-1") -> RSConnectExecutor: executor = RSConnectExecutor.__new__(RSConnectExecutor) executor.remote_server = ConnectCloudServer(account_name, access_token="at", account_id=account_id) executor.client = mock.MagicMock(spec=ConnectCloudClient) @@ -4194,7 +4194,7 @@ def setUp(self): store_patch.start() self.addCleanup(store_patch.stop) - def _stored(self, field: str, nickname: str = "cloud") -> Optional[str]: + def _stored(self, field: str, nickname: str = "cloud") -> str | None: return self.keyring.get_password("rsconnect-python", "%s#%s:%s" % (API, nickname, field)) def _store_in_keyring(self, field: str, value: str, nickname: str = "cloud") -> None: @@ -4341,7 +4341,7 @@ def test_a_keyring_read_failure_leaves_the_client_secret_where_it_is(self): secret_username = "%s#cloud:%s" % (API, "client_secret") stored = self.keyring.get_password - def failing_read(service: str, username: str) -> Optional[str]: + def failing_read(service: str, username: str) -> str | None: if username == secret_username: raise Exception("keychain locked") return stored(service, username) diff --git a/tests/test_environment.py b/tests/test_environment.py index c80713a59..f2c7bc1ae 100644 --- a/tests/test_environment.py +++ b/tests/test_environment.py @@ -1158,7 +1158,7 @@ def test_minor_python_override(self): ) def test_python_interpreter(self): - current_python_version = ".".join((str(v) for v in sys.version_info[:3])) + current_python_version = ".".join(str(v) for v in sys.version_info[:3]) with mock.patch.object(rsconnect.environment.logger, "warning") as mock_warning: result = Environment.create_python_environment(get_dir("pip1")) diff --git a/tests/test_http_support.py b/tests/test_http_support.py index 84feddf3b..0134c6640 100644 --- a/tests/test_http_support.py +++ b/tests/test_http_support.py @@ -2,7 +2,8 @@ import time from contextlib import ExitStack, contextmanager from http.server import BaseHTTPRequestHandler, HTTPServer as _TestHTTPServer -from typing import Any, Generator, cast +from typing import Any, cast +from collections.abc import Generator from unittest import TestCase from rsconnect.http_support import ( @@ -307,7 +308,7 @@ def test_header_stuff(self): self.assertEqual(server._headers["Authorization"], "Connect-Bootstrap my.jwt.token") -class FakeSetCookieResponse(object): +class FakeSetCookieResponse: def __init__(self, data): self._data = [("Set-Cookie", term) for term in data] diff --git a/tests/test_json_web_token.py b/tests/test_json_web_token.py index d227a11cf..b221ce9ae 100644 --- a/tests/test_json_web_token.py +++ b/tests/test_json_web_token.py @@ -4,7 +4,7 @@ import json import jwt -from datetime import datetime, timedelta, timezone +from datetime import datetime, timedelta, UTC import os from rsconnect.exception import RSConnectException @@ -212,11 +212,11 @@ def test_produce_bootstrap_output(self): with pytest.raises(RSConnectException): produce_bootstrap_output(400, {"api_key": api_key}) - expected_successful_result = json.loads(open("tests/testdata/initial-admin-responses/success.json", "r").read()) + expected_successful_result = json.loads(open("tests/testdata/initial-admin-responses/success.json").read()) self.assertEqual(produce_bootstrap_output(200, {"api_key": api_key}), expected_successful_result) expected_forbidden_result = json.loads( - open("tests/testdata/initial-admin-responses/forbidden_error.json", "r").read() + open("tests/testdata/initial-admin-responses/forbidden_error.json").read() ) self.assertEqual(produce_bootstrap_output(403, None), expected_forbidden_result) self.assertEqual(produce_bootstrap_output(403, {}), expected_forbidden_result) @@ -224,7 +224,7 @@ def test_produce_bootstrap_output(self): self.assertEqual(produce_bootstrap_output(403, {"something": "else"}), expected_forbidden_result) expected_unauthorized_error_result = json.loads( - open("tests/testdata/initial-admin-responses/unauthorized_error.json", "r").read() + open("tests/testdata/initial-admin-responses/unauthorized_error.json").read() ) self.assertEqual(produce_bootstrap_output(401, None), expected_unauthorized_error_result) self.assertEqual(produce_bootstrap_output(401, {}), expected_unauthorized_error_result) @@ -232,16 +232,14 @@ def test_produce_bootstrap_output(self): self.assertEqual(produce_bootstrap_output(401, {"something": "else"}), expected_unauthorized_error_result) expected_not_found_error_result = json.loads( - open("tests/testdata/initial-admin-responses/not_found_error.json", "r").read() + open("tests/testdata/initial-admin-responses/not_found_error.json").read() ) self.assertEqual(produce_bootstrap_output(404, None), expected_not_found_error_result) self.assertEqual(produce_bootstrap_output(404, {}), expected_not_found_error_result) self.assertEqual(produce_bootstrap_output(404, {"api_key": ""}), expected_not_found_error_result) self.assertEqual(produce_bootstrap_output(404, {"something": "else"}), expected_not_found_error_result) - expected_other_error_result = json.loads( - open("tests/testdata/initial-admin-responses/other_error.json", "r").read() - ) + expected_other_error_result = json.loads(open("tests/testdata/initial-admin-responses/other_error.json").read()) self.assertEqual(produce_bootstrap_output(500, None), expected_other_error_result) self.assertEqual(produce_bootstrap_output(500, {}), expected_other_error_result) self.assertEqual(produce_bootstrap_output(500, {"api_key": ""}), expected_other_error_result) @@ -289,7 +287,7 @@ def test_new_token_empty_custom_claims(self): decoder = JWTDecoder("audience", self.secret_key) exp = timedelta(hours=5) - current_datetime = datetime.now(tz=timezone.utc) + current_datetime = datetime.now(tz=UTC) expected_exp = int((current_datetime + exp).timestamp()) expected_iat = int(current_datetime.timestamp()) @@ -311,7 +309,7 @@ def test_new_token_populated_custom_claims(self): decoder = JWTDecoder("audience", self.secret_key) exp = timedelta(hours=5) - current_datetime = datetime.now(tz=timezone.utc) + current_datetime = datetime.now(tz=UTC) expected_exp = int((current_datetime + exp).timestamp()) expected_iat = int(current_datetime.timestamp()) @@ -347,7 +345,7 @@ def test_token_generator_bootstrap(self): self.assertEqual(payload.keys(), set(["exp", "iss", "aud", "iat", "scope"])) - current_datetime = datetime.now(tz=timezone.utc) + current_datetime = datetime.now(tz=UTC) self.assert_bootstrap_jwt_is_valid(payload, current_datetime) def test_token_generator_invalid_verification_secret(self): @@ -373,7 +371,7 @@ def test_token_workflow(self): decoder = JWTDecoder(DEFAULT_AUDIENCE, self.secret_key) payload = decoder.decode_token(bootstrap_token) - current_datetime = datetime.now(tz=timezone.utc) + current_datetime = datetime.now(tz=UTC) self.assert_bootstrap_jwt_is_valid(payload, current_datetime) # BEGIN ACTUAL TEST @@ -394,7 +392,7 @@ def test_token_workflow(self): # decode the token test_payload = decoder.decode_token(test_bootstrap_token) - test_datetime = datetime.now(tz=timezone.utc) + test_datetime = datetime.now(tz=UTC) # assert we have a valid token self.assert_bootstrap_jwt_is_valid(test_payload, test_datetime) diff --git a/tests/test_main.py b/tests/test_main.py index 4a7e51dfd..fd2f4d85f 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -252,7 +252,7 @@ def test_deploy_draft(self, command, target, expected_activate, caplog): httpretty.register_uri( httpretty.GET, "http://fake_server/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -654,7 +654,7 @@ def test_deploy_verify_before_activate(self, caplog): httpretty.register_uri( httpretty.GET, "http://fake_server/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -846,7 +846,7 @@ def test_deploy_verify_before_activate_unsupported_server(self, caplog): httpretty.register_uri( httpretty.GET, "http://fake_server/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -967,7 +967,7 @@ def test_deploy_draft_unsupported_server(self): httpretty.register_uri( httpretty.GET, "http://fake_server/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1038,7 +1038,7 @@ def _register_quiet_deploy_routes(self, task_body): httpretty.register_uri( httpretty.GET, "http://fake_server/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1243,7 +1243,7 @@ def test_deploy_bundle(self, caplog): httpretty.register_uri( httpretty.GET, "http://fake_server/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1359,7 +1359,7 @@ def _register_deploy_endpoints(self, guid, existing_title, patch_calls, app_mode httpretty.register_uri( httpretty.GET, "http://fake_server/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1658,7 +1658,7 @@ def test_deploy_manifest_shinyapps(self, mock_open_browser): httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/users/me", - body=open("tests/testdata/rstudio-responses/get-user.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-user.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1666,14 +1666,14 @@ def test_deploy_manifest_shinyapps(self, mock_open_browser): httpretty.GET, "https://api.shinyapps.io/v1/applications" "?filter=name:like:shinyapp&offset=0&count=100&use_advanced_filters=true", - body=open("tests/testdata/rstudio-responses/get-applications.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-applications.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/accounts/", - body=open("tests/testdata/rstudio-responses/get-accounts.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-accounts.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1687,7 +1687,7 @@ def post_application_callback(request, uri, response_headers): return [ 201, {"Content-Type": "application/json"}, - open("tests/testdata/rstudio-responses/application.json", "r").read(), + open("tests/testdata/rstudio-responses/application.json").read(), ] httpretty.register_uri( @@ -1730,7 +1730,7 @@ def post_bundle_callback(request, uri, response_headers): return [ 201, {"Content-Type": "application/json"}, - open("tests/testdata/rstudio-responses/create-bundle.json", "r").read(), + open("tests/testdata/rstudio-responses/create-bundle.json").read(), ] httpretty.register_uri( @@ -1769,7 +1769,7 @@ def post_bundle_status_callback(request, uri, response_headers): httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/bundles/12640", - body=open("tests/testdata/rstudio-responses/get-accounts.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-accounts.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1783,7 +1783,7 @@ def post_deploy_callback(request, uri, response_headers): return [ 303, {"Location": "https://api.shinyapps.io/v1/tasks/333"}, - open("tests/testdata/rstudio-responses/post-deploy.json", "r").read(), + open("tests/testdata/rstudio-responses/post-deploy.json").read(), ] httpretty.register_uri( @@ -1795,7 +1795,7 @@ def post_deploy_callback(request, uri, response_headers): httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/tasks/333", - body=open("tests/testdata/rstudio-responses/get-task.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-task.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1834,7 +1834,7 @@ def test_redeploy_manifest_shinyapps(self, mock_open_browser): httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/users/me", - body=open("tests/testdata/rstudio-responses/get-user.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-user.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1842,14 +1842,14 @@ def test_redeploy_manifest_shinyapps(self, mock_open_browser): httpretty.GET, "https://api.shinyapps.io/v1/applications" "?filter=name:like:shinyapp&offset=0&count=100&use_advanced_filters=true", - body=open("tests/testdata/rstudio-responses/get-applications.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-applications.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/accounts/", - body=open("tests/testdata/rstudio-responses/get-accounts.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-accounts.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1857,7 +1857,7 @@ def test_redeploy_manifest_shinyapps(self, mock_open_browser): httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/applications/8442", - body=open("tests/testdata/rstudio-responses/application.json", "r").read(), + body=open("tests/testdata/rstudio-responses/application.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1896,7 +1896,7 @@ def post_bundle_callback(request, uri, response_headers): return [ 201, {"Content-Type": "application/json"}, - open("tests/testdata/rstudio-responses/create-bundle.json", "r").read(), + open("tests/testdata/rstudio-responses/create-bundle.json").read(), ] httpretty.register_uri( @@ -1935,7 +1935,7 @@ def post_bundle_status_callback(request, uri, response_headers): httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/bundles/12640", - body=open("tests/testdata/rstudio-responses/get-accounts.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-accounts.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -1949,7 +1949,7 @@ def post_deploy_callback(request, uri, response_headers): return [ 303, {"Location": "https://api.shinyapps.io/v1/tasks/333"}, - open("tests/testdata/rstudio-responses/post-deploy.json", "r").read(), + open("tests/testdata/rstudio-responses/post-deploy.json").read(), ] httpretty.register_uri( @@ -1961,7 +1961,7 @@ def post_deploy_callback(request, uri, response_headers): httpretty.register_uri( httpretty.GET, "https://api.shinyapps.io/v1/tasks/333", - body=open("tests/testdata/rstudio-responses/get-task.json", "r").read(), + body=open("tests/testdata/rstudio-responses/get-task.json").read(), adding_headers={"Content-Type": "application/json"}, status=200, ) @@ -2282,7 +2282,7 @@ def test_bootstrap(self): self.assertEqual(result.exit_code, 0, result.output) json_output = json.loads(result.output) - expected_output = json.loads(open("tests/testdata/initial-admin-responses/success.json", "r").read()) + expected_output = json.loads(open("tests/testdata/initial-admin-responses/success.json").read()) self.assertEqual(json_output, expected_output) @httpretty.activate(verbose=True, allow_net_connect=False) @@ -2310,7 +2310,7 @@ def test_bootstrap_experimental_fallback(self): self.assertEqual(result.exit_code, 0, result.output) json_output = json.loads(result.output) - expected_output = json.loads(open("tests/testdata/initial-admin-responses/success.json", "r").read()) + expected_output = json.loads(open("tests/testdata/initial-admin-responses/success.json").read()) self.assertEqual(json_output, expected_output) @httpretty.activate(verbose=True, allow_net_connect=False) @@ -2341,7 +2341,7 @@ def test_bootstrap_env_var(self): self.assertEqual(result.exit_code, 0, result.output) json_output = json.loads(result.output) - expected_output = json.loads(open("tests/testdata/initial-admin-responses/success.json", "r").read()) + expected_output = json.loads(open("tests/testdata/initial-admin-responses/success.json").read()) self.assertEqual(json_output, expected_output) del os.environ[SECRET_KEY_ENV] @@ -2366,7 +2366,7 @@ def test_bootstrap_misc_error(self): self.assertEqual(result.exit_code, 0, result.output) json_output = json.loads(result.output) - expected_output = json.loads(open("tests/testdata/initial-admin-responses/other_error.json", "r").read()) + expected_output = json.loads(open("tests/testdata/initial-admin-responses/other_error.json").read()) self.assertEqual(json_output, expected_output) @httpretty.activate(verbose=True, allow_net_connect=False) @@ -2392,7 +2392,7 @@ def test_bootstrap_not_found_error(self): self.assertEqual(result.exit_code, 0, result.output) json_output = json.loads(result.output) - expected_output = json.loads(open("tests/testdata/initial-admin-responses/not_found_error.json", "r").read()) + expected_output = json.loads(open("tests/testdata/initial-admin-responses/not_found_error.json").read()) self.assertEqual(json_output, expected_output) @httpretty.activate(verbose=True, allow_net_connect=False) @@ -2414,7 +2414,7 @@ def test_bootstrap_forbidden_error(self): self.assertEqual(result.exit_code, 0, result.output) json_output = json.loads(result.output) - expected_output = json.loads(open("tests/testdata/initial-admin-responses/forbidden_error.json", "r").read()) + expected_output = json.loads(open("tests/testdata/initial-admin-responses/forbidden_error.json").read()) self.assertEqual(json_output, expected_output) @@ -2438,7 +2438,7 @@ def test_bootstrap_unauthorized(self): self.assertEqual(result.exit_code, 0, result.output) json_output = json.loads(result.output) - expected_output = json.loads(open("tests/testdata/initial-admin-responses/unauthorized_error.json", "r").read()) + expected_output = json.loads(open("tests/testdata/initial-admin-responses/unauthorized_error.json").read()) self.assertEqual(json_output, expected_output) diff --git a/tests/test_main_content.py b/tests/test_main_content.py index 0f37c47db..f4205ea63 100644 --- a/tests/test_main_content.py +++ b/tests/test_main_content.py @@ -30,7 +30,7 @@ def register_content_endpoints(i: int, guid: str): httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/content/{guid}", - body=open(f"tests/testdata/connect-responses/describe-content-{i}.json", "r").read(), + body=open(f"tests/testdata/connect-responses/describe-content-{i}.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( @@ -61,19 +61,19 @@ def register_content_endpoints(i: int, guid: str): httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/server_settings", - body=open("tests/testdata/connect-responses/server_settings.json", "r").read(), + body=open("tests/testdata/connect-responses/server_settings.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/content", - body=open("tests/testdata/connect-responses/list-content.json", "r").read(), + body=open("tests/testdata/connect-responses/list-content.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( diff --git a/tests/test_main_environment.py b/tests/test_main_environment.py index 9a42d4d28..ac4fcbfe8 100644 --- a/tests/test_main_environment.py +++ b/tests/test_main_environment.py @@ -15,37 +15,37 @@ def register_uris(connect_server: str): httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/server_settings", - body=open("tests/testdata/connect-responses/server_settings.json", "r").read(), + body=open("tests/testdata/connect-responses/server_settings.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/environments", - body=open("tests/testdata/connect-responses/list-environments.json", "r").read(), + body=open("tests/testdata/connect-responses/list-environments.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/environments/{ENVIRONMENT_GUID}", - body=open("tests/testdata/connect-responses/get-environment.json", "r").read(), + body=open("tests/testdata/connect-responses/get-environment.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.POST, f"{connect_server}/__api__/v1/environments", - body=open("tests/testdata/connect-responses/get-environment.json", "r").read(), + body=open("tests/testdata/connect-responses/get-environment.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.PUT, f"{connect_server}/__api__/v1/environments/{ENVIRONMENT_GUID}", - body=open("tests/testdata/connect-responses/get-environment.json", "r").read(), + body=open("tests/testdata/connect-responses/get-environment.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( @@ -57,13 +57,13 @@ def register_uris(connect_server: str): httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/environments/{ENVIRONMENT_GUID}/permissions", - body=open("tests/testdata/connect-responses/list-environment-permissions.json", "r").read(), + body=open("tests/testdata/connect-responses/list-environment-permissions.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.POST, f"{connect_server}/__api__/v1/environments/{ENVIRONMENT_GUID}/permissions", - body=open("tests/testdata/connect-responses/get-environment-permission.json", "r").read(), + body=open("tests/testdata/connect-responses/get-environment-permission.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( @@ -104,13 +104,13 @@ def test_environment_list_empty(self): httpretty.register_uri( httpretty.GET, f"{self.connect_server}/__api__/server_settings", - body=open("tests/testdata/connect-responses/server_settings.json", "r").read(), + body=open("tests/testdata/connect-responses/server_settings.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{self.connect_server}/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( diff --git a/tests/test_main_integration.py b/tests/test_main_integration.py index e53820541..befac1e5e 100644 --- a/tests/test_main_integration.py +++ b/tests/test_main_integration.py @@ -15,37 +15,37 @@ def register_uris(connect_server: str): httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/server_settings", - body=open("tests/testdata/connect-responses/server_settings.json", "r").read(), + body=open("tests/testdata/connect-responses/server_settings.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/oauth/integrations", - body=open("tests/testdata/connect-responses/list-integrations.json", "r").read(), + body=open("tests/testdata/connect-responses/list-integrations.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/oauth/integrations/{INTEGRATION_GUID}", - body=open("tests/testdata/connect-responses/get-integration.json", "r").read(), + body=open("tests/testdata/connect-responses/get-integration.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.POST, f"{connect_server}/__api__/v1/oauth/integrations", - body=open("tests/testdata/connect-responses/get-integration.json", "r").read(), + body=open("tests/testdata/connect-responses/get-integration.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.PATCH, f"{connect_server}/__api__/v1/oauth/integrations/{INTEGRATION_GUID}", - body=open("tests/testdata/connect-responses/get-integration.json", "r").read(), + body=open("tests/testdata/connect-responses/get-integration.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( @@ -57,13 +57,13 @@ def register_uris(connect_server: str): httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/oauth/templates", - body=open("tests/testdata/connect-responses/list-templates.json", "r").read(), + body=open("tests/testdata/connect-responses/list-templates.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/oauth/templates/custom", - body=open("tests/testdata/connect-responses/get-template.json", "r").read(), + body=open("tests/testdata/connect-responses/get-template.json").read(), adding_headers={"Content-Type": "application/json"}, ) diff --git a/tests/test_main_system_caches.py b/tests/test_main_system_caches.py index 5425a208a..e554081d0 100644 --- a/tests/test_main_system_caches.py +++ b/tests/test_main_system_caches.py @@ -21,13 +21,13 @@ def register_server_validation_uris(connect_server: str): httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/server_settings", - body=open("tests/testdata/connect-responses/server_settings.json", "r").read(), + body=open("tests/testdata/connect-responses/server_settings.json").read(), adding_headers={"Content-Type": "application/json"}, ) httpretty.register_uri( httpretty.GET, f"{connect_server}/__api__/v1/user", - body=open("tests/testdata/connect-responses/me.json", "r").read(), + body=open("tests/testdata/connect-responses/me.json").read(), adding_headers={"Content-Type": "application/json"}, ) diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 24f44f914..46e03f968 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -180,7 +180,7 @@ def test_save_and_load(self): self.assertTrue(exists(path)) - with open(path, "r") as f: + with open(path) as f: data = f.read() self.assertIn("foo", data) @@ -467,7 +467,7 @@ def fail_primary(path, flags, mode, *args, **kwargs): self.assertEqual(store.get_path(), secondary) self.assertFalse(exists(primary)) self.assertEqual(set(os.listdir(os.path.dirname(primary))), set()) - with open(secondary, "r", encoding="utf-8") as metadata_file: + with open(secondary, encoding="utf-8") as metadata_file: self.assertEqual(json.load(metadata_file), store._data) def test_private_store_updates_symlink_target_in_place(self): @@ -565,7 +565,7 @@ def test_private_store_updates_existing_file_in_read_only_parent(self): self.assertEqual(os.stat(path).st_ino, previous_inode) self.assertEqual(set(os.listdir(parent)), files_before) - with open(path, "r", encoding="utf-8") as metadata_file: + with open(path, encoding="utf-8") as metadata_file: self.assertEqual(json.load(metadata_file), store._data) def test_save_rewrites_when_data_changed(self): @@ -649,7 +649,7 @@ def test_local_save_load(self): path = join(self.tempdir, "rsconnect-python", "notebook.json") self.assertTrue(exists(path)) - with open(path, "r") as f: + with open(path) as f: data = f.read() self.assertIn("http://dev", data) diff --git a/tests/test_oauth.py b/tests/test_oauth.py index bab8ce33e..5e5b4a4a3 100644 --- a/tests/test_oauth.py +++ b/tests/test_oauth.py @@ -779,7 +779,7 @@ def test_refresh_falls_back_to_store( mock_keyring_store: MagicMock, mock_keyring_get: MagicMock, mock_http_server_cls: MagicMock, - server_name: "str | None", + server_name: str | None, get_by_name_rv: Any, get_by_url_rv: Any, ): diff --git a/tests/test_oauth_token.py b/tests/test_oauth_token.py index efc5b3823..93b595b03 100644 --- a/tests/test_oauth_token.py +++ b/tests/test_oauth_token.py @@ -5,7 +5,8 @@ import inspect import json import threading -from typing import Any, Iterator +from typing import Any +from collections.abc import Iterator from unittest.mock import MagicMock, patch import click diff --git a/tests/test_package_installer.py b/tests/test_package_installer.py index 005c632c7..6a6c6e153 100644 --- a/tests/test_package_installer.py +++ b/tests/test_package_installer.py @@ -50,7 +50,7 @@ def test_deploy_quarto_passes_package_installer(tmp_path: pathlib.Path): (tmp_path / "doc.qmd").write_text("---\ntitle: t\n---\n") (tmp_path / "requirements.txt").write_text("jupyter\n") real_create = Environment.create_python_environment - environments: typing.List[Environment] = [] + environments: list[Environment] = [] def recording_create(*args: typing.Any, **kwargs: typing.Any) -> Environment: environment = real_create(*args, **kwargs) diff --git a/tests/test_preflight_integration.py b/tests/test_preflight_integration.py index 1adc6bbd9..0a9331231 100644 --- a/tests/test_preflight_integration.py +++ b/tests/test_preflight_integration.py @@ -7,7 +7,7 @@ import subprocess import sys from pathlib import Path -from typing import Any, Dict, List +from typing import Any import pytest @@ -34,7 +34,7 @@ def _live_client(server_url: str, api_key: str) -> RSConnectClient: return RSConnectClient(RSConnectServer(server_url, api_key, insecure=_insecure(), ca_data=ca_data)) -def _cli_environment(home: Path, api_key: str) -> Dict[str, str]: +def _cli_environment(home: Path, api_key: str) -> dict[str, str]: home.mkdir(parents=True, exist_ok=True) environment = os.environ.copy() for name in ( @@ -96,7 +96,7 @@ def _run_preflight( ) -def _report(result: subprocess.CompletedProcess[str]) -> Dict[str, Any]: +def _report(result: subprocess.CompletedProcess[str]) -> dict[str, Any]: try: report = json.loads(result.stdout) except json.JSONDecodeError as err: @@ -107,7 +107,7 @@ def _report(result: subprocess.CompletedProcess[str]) -> Dict[str, Any]: return report -def _files(project: Path) -> Dict[str, bytes]: +def _files(project: Path) -> dict[str, bytes]: return {path.name: path.read_bytes() for path in project.iterdir()} @@ -158,7 +158,7 @@ def test_live_nodejs_preflight_checks_server_settings_without_writing_project_fi installations = settings.get("installations") assert isinstance(installations, list), settings - versions: List[str] = [ + versions: list[str] = [ item["version"] for item in installations if isinstance(item, dict) and isinstance(item.get("version"), str) ] publishable_versions = [ diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 66316afa9..0e80a9d99 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -152,7 +152,7 @@ def test_quickstart_quarto_shiny_not_supported(runner: CliRunner, in_tmp_cwd: pa def test_quickstart_delegates_to_run_quickstart( runner: CliRunner, monkeypatch: pytest.MonkeyPatch, - args: typing.List[str], + args: list[str], expected: typing.Mapping[str, typing.Any], ): run_quickstart = mock.Mock() @@ -848,7 +848,7 @@ def test_quickstart_voila_and_notebook_share_template(runner: CliRunner, in_tmp_ def test_install_venv_clears_virtual_env(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path): """``uv`` must not see the developer's activated venv (avoids the venv-mismatch warning).""" monkeypatch.setenv("VIRTUAL_ENV", "/some/parent/.venv") - captured_envs: typing.List[typing.Mapping[str, str]] = [] + captured_envs: list[typing.Mapping[str, str]] = [] def fake_run(cmd, cwd, env): captured_envs.append(env) @@ -878,10 +878,10 @@ def test_quickstart_venv_interpreter( runner: CliRunner, in_tmp_cwd: pathlib.Path, monkeypatch: pytest.MonkeyPatch, - extra_args: typing.List[str], - expected_python: typing.Optional[str], + extra_args: list[str], + expected_python: str | None, ): - calls: typing.List[typing.Optional[str]] = [] + calls: list[str | None] = [] monkeypatch.setattr( "rsconnect.quickstart.quickstart._install_venv", lambda target, python=None: calls.append(python), @@ -892,7 +892,7 @@ def test_quickstart_venv_interpreter( def test_install_venv_passes_python(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path): - commands: typing.List[typing.List[str]] = [] + commands: list[list[str]] = [] def fake_run(cmd, cwd, env): commands.append(cmd) diff --git a/tests/test_snowflake.py b/tests/test_snowflake.py index 763eeecf8..be2781577 100644 --- a/tests/test_snowflake.py +++ b/tests/test_snowflake.py @@ -2,7 +2,6 @@ import logging import sys from subprocess import CalledProcessError -from typing import List import pytest from pytest import LogCaptureFixture, MonkeyPatch @@ -92,7 +91,7 @@ def test_ensure_snow_installed_binary(monkeypatch: MonkeyPatch, caplog: LogCaptu monkeypatch.setattr("builtins.__import__", mock_failed_import) # Mock run to return success - def mock_run(cmd: List[str], **kwargs): + def mock_run(cmd: list[str], **kwargs): assert cmd == ["snow", "--version"] assert kwargs.get("capture_output") is True assert kwargs.get("check") is True @@ -117,7 +116,7 @@ def test_ensure_snow_installed_nobinary(monkeypatch: MonkeyPatch, caplog: LogCap monkeypatch.setattr("builtins.__import__", mock_failed_import) # Mock run to raise FileNotFoundError - def mock_run(cmd: List[str], **kwargs): + def mock_run(cmd: list[str], **kwargs): if cmd == ["snow", "--version"]: raise FileNotFoundError("No such file or directory: 'snow'") return MockRunResult(returncode=0) @@ -143,7 +142,7 @@ def test_ensure_snow_installed_failing_binary(monkeypatch: MonkeyPatch, caplog: monkeypatch.setattr("builtins.__import__", mock_failed_import) # Mock run to raise CalledProcessError - def mock_run(cmd: List[str], **kwargs): + def mock_run(cmd: list[str], **kwargs): if cmd == ["snow", "--version"]: raise CalledProcessError(returncode=1, cmd=cmd, output="", stderr="Command failed with exit code 1") return MockRunResult(returncode=0) diff --git a/tests/test_target_inference.py b/tests/test_target_inference.py index 91927e72d..67574fd1a 100644 --- a/tests/test_target_inference.py +++ b/tests/test_target_inference.py @@ -9,7 +9,7 @@ import os import tempfile import unittest -from typing import Any, Optional +from typing import Any from unittest import mock import click @@ -152,7 +152,7 @@ def _cloud( self, name: str = "cloud", account: str = "acme", - account_id: Optional[str] = "acct-1", + account_id: str | None = "acct-1", default: bool = False, ) -> None: self.store.set(