Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/commands/quickstart.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
# Python version selection

Without `--python`, quickstart uses the newest usable Python installation
marked publishable for new content on the selected Posit Connect server.
It writes a `>=major.minor` requirement and asks uv to create the environment
with that major/minor. uv may download Python according to your uv settings.
Server selection and credentials use the usual `--name`, `--server`,
`--api-key`, TLS options, environment variables, and saved servers.

If no server is configured, quickstart uses the Python interpreter running
rsconnect. If the server cannot be queried or credentials are missing, it
warns and uses that interpreter without checking server compatibility. If a
successful lookup finds no usable publishable Python, quickstart fails: check
the server's Python configuration or use `--python`. A failed Python download
or dependency installation also fails and removes the incomplete project.
If several servers are saved without a default, select one with `--name` or
`--server`, or set a default. Invalid server nicknames and CA certificate paths
are errors.

`--python` overrides discovery and makes no server request. A major/minor
version permits any patch release, a full version is exact, and a specifier
such as `>=3.10,<3.13` is used as supplied. Explicit server options are ignored
when `--python` is supplied.

::: mkdocs-click
:module: rsconnect.main
:command: quickstart
82 changes: 77 additions & 5 deletions rsconnect/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2034,7 +2034,8 @@ def info(file: str):
# vocabulary.
type=click.Choice(AppModes.cli_aliases()),
)
@click.argument("name", metavar="NAME")
@click.argument("project_name", metavar="NAME")
@server_args
@click.option(
"--python",
"python_version",
Expand All @@ -2044,18 +2045,89 @@ def info(file: str):
"Python version for 'requires-python' in the generated pyproject.toml. "
"A bare 'major.minor' like '3.10' means any 3.10.x; a full '3.11.14' is "
"exact; pass an operator for full control (e.g. '>=3.11' or "
"'>=3.11,<3.14'). Defaults to '>=<major.minor>' of the interpreter "
"running rsconnect."
"'>=3.11,<3.14'). By default, use the newest publishable Python on "
"the selected Connect server, or the interpreter running rsconnect."
),
)
@cli_exception_handler
def quickstart(app_type: str, name: str, python_version: Optional[str]):
@click.pass_context
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],
insecure: bool,
cacert: Optional[str],
verbose: int,
):
# Resolve ``run_quickstart`` through the module at call time so tests can
# monkeypatch ``rsconnect.quickstart.quickstart.run_quickstart`` without
# binding a stale reference into ``main``'s namespace at import time.
from .quickstart.quickstart import run_quickstart

run_quickstart(app_type=app_type, name=name, python_version=python_version)
set_verbosity(verbose)

if python_version is not None:
ignored_options = [
option
for option in ("name", "server", "api_key", "insecure", "cacert")
if validation.get_parameter_source_name_from_ctx(option, ctx) == "COMMANDLINE"
]
if ignored_options:
click.echo("Server options are ignored because --python was supplied.")

def server_python_settings() -> Optional[tuple[object, str]]:
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:
read_certificate_file(cacert)
resolved = server_store.resolve(name, server)
if not resolved.url:
if server_store.count() > 1:
warn_user(
"Warning: Multiple servers are saved with no default. "
"Use --name or --server, or set a default, to check server compatibility."
)
return None, "fallback"
return None

if not (api_key or resolved.api_key or resolved.oauth_client_id):
warn_user(
"Warning: Could not check the Connect server's Python settings: "
"No Connect credentials are available; use --api-key or log in with rsconnect login.\n"
"Server compatibility was not checked."
)
return None, "fallback"

# The executor's validation requires a target even when the store
# can resolve a single saved server without an explicit default.
effective_name = name or (resolved.name if not server else None)
executor = RSConnectExecutor(
ctx, effective_name, server, api_key, insecure=insecure, cacert=cacert, logger=None
)
if not isinstance(executor.remote_server, RSConnectServer) or not isinstance(executor.client, RSConnectClient):
raise RSConnectException("The selected target is not a Posit Connect server.")
remote = executor.remote_server
click.echo(f"Checking Python versions on {remote.url}...")
try:
with executor.client:
return executor.client.python_settings(), remote.url
except Exception as exc:
warn_user(
f"Warning: Could not check the Connect server's Python settings: {exc}\n"
"Server compatibility was not checked."
)
return None, "fallback"

run_quickstart(
app_type=app_type,
name=project_name,
python_version=python_version,
server_python_settings=server_python_settings,
)


@cli.group(no_args_is_help=True, help="Deploy content to Posit Connect, Posit Connect Cloud, or shinyapps.io.")
Expand Down
3 changes: 2 additions & 1 deletion rsconnect/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import fnmatch
import pathlib
import re
from typing import Callable, Literal, Optional, TypedDict, cast
from typing import Callable, Literal, NotRequired, Optional, TypedDict, cast

import click
import semver
Expand Down Expand Up @@ -610,6 +610,7 @@ class PyInstallation(TypedDict):
version: str
cluster_name: str
image_name: str
publishable: NotRequired[bool]


class BuildOutputDTO(TypedDict):
Expand Down
61 changes: 48 additions & 13 deletions rsconnect/quickstart/quickstart.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ def run_quickstart(
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,
) -> pathlib.Path:
"""Scaffold a new Connect project of ``app_type`` named ``name``.
Expand All @@ -65,8 +66,8 @@ def run_quickstart(
that begins with a specifier operator (e.g. ``>=3.11`` or
``>=3.11,<3.14``) is used verbatim. A bare version is padded to at
most three segments: ``3.10`` -> ``==3.10.*`` (any 3.10.x) and
``3.11.14`` -> ``==3.11.14`` (exact). Defaults to ``>=<major.minor>``
of the interpreter running ``rsconnect``.
``3.11.14`` -> ``==3.11.14`` (exact).
:param server_python_settings: optional lazy server settings lookup.
:param pathlib.Path cwd: override the working directory (testing hook);
defaults to :func:`pathlib.Path.cwd`.
"""
Expand All @@ -93,13 +94,27 @@ 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).
# Without ``--python`` we track the running interpreter's ``major.minor``.
venv_python: typing.Optional[str] = None
if python_version is None:
requires_python = _REQUIRES_PYTHON
venv_python = sys.executable
source = "the Python interpreter running rsconnect"
settings = server_python_settings() if server_python_settings else None
if settings is not None:
data, server = settings
if server == "fallback" and data is None:
source = "the Python interpreter running rsconnect; server compatibility not checked"
else:
version = _newest_publishable_python(data)
requires_python = f">={version}"
venv_python = version
source = f"the Posit Connect server {server}"
elif python_version[:1] in {"=", "<", ">", "!", "~"}:
requires_python = python_version
source = "the --python override"
else:
requires_python = "==" + ".".join((python_version.split(".") + ["*"])[:3])
source = "the --python override"

# Atomicity: after ``mkdir`` succeeds, any failure in the rest of the
# pipeline must remove ``./<name>/`` so the user sees "all or nothing."
Expand All @@ -108,10 +123,7 @@ def run_quickstart(
target.mkdir()
try:
_scaffold(target, name=name, spec=spec, requires_python=requires_python)
# Without ``--python``, build the venv on the running interpreter.
# Otherwise uv picks the newest Python matching ``requires-python``,
# which may be too new for some dependencies to have wheels yet.
_install_venv(target, python=sys.executable if python_version is None else None)
_install_venv(target, python=venv_python)
except BaseException:
shutil.rmtree(target, ignore_errors=True)
raise
Expand All @@ -120,10 +132,34 @@ def run_quickstart(
# BrokenPipeError when piping to ``head``) must not invalidate the
# on-disk project. The README carries the same two commands, so the
# user can recover them even if this echo fails.
_emit_summary(target, name=name, spec=spec)
_emit_summary(target, name=name, spec=spec, requires_python=requires_python, source=source)
return target


def _newest_publishable_python(settings: object) -> str:
installations = (
typing.cast(typing.Mapping[str, object], settings).get("installations") if isinstance(settings, dict) else None
)
versions: list[tuple[int, ...]] = []
if isinstance(installations, list):
for item in typing.cast(typing.List[object], installations):
if not isinstance(item, dict):
continue
installation = typing.cast(typing.Mapping[str, object], item)
if installation.get("publishable") is not True:
continue
version = installation.get("version")
if isinstance(version, str) and re.fullmatch(r"[0-9]+\.[0-9]+(?:\.[0-9]+)?", version):
versions.append(tuple(int(part) for part in version.split(".")))
if not versions:
raise RSConnectException(
"The Connect server has no usable Python installation marked publishable for new content. "
"Check the server's Python configuration or use --python to bypass discovery."
)
selected = max(versions)
return f"{selected[0]}.{selected[1]}"


# ---------------------------------------------------------------------------
# Pre-flight checks
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -392,9 +428,7 @@ def _load_template(path: str) -> str:
# ``requires-python`` is the single source of truth for the scaffold's Python
# requirement: ``rsconnect deploy pyproject`` reads ``pyproject.toml``, so
# emitting a separate ``.python-version`` pin would only duplicate this value.
# The floor tracks the interpreter that ran ``rsconnect quickstart`` so the
# scaffold matches the developer's working environment without committing the
# project to any version older than what its author has actually used.
# The running interpreter is the fallback when no server can be consulted.
_REQUIRES_PYTHON = ">={}.{}".format(*sys.version_info[:2])

_GITIGNORE_BODY = """\
Expand All @@ -410,7 +444,7 @@ def _load_template(path: str) -> str:
def _render_pyproject(*, name: str, spec: TemplateSpec, requires_python: str) -> str:
# The per-mode template owns the literal TOML, including ``app_mode``,
# ``entrypoint`` and the dependency list. Only ``$name`` (project name)
# and ``$requires_python`` (from ``--python`` or the running interpreter)
# and ``$requires_python`` (selected for this scaffold)
# vary at scaffold time.
return string.Template(_load_template(spec.pyproject_template)).substitute(
name=name, requires_python=requires_python
Expand Down Expand Up @@ -472,14 +506,15 @@ def _install_venv(target: pathlib.Path, python: typing.Optional[str] = None) ->
# ---------------------------------------------------------------------------


def _emit_summary(target: pathlib.Path, *, name: str, spec: TemplateSpec) -> None:
def _emit_summary(target: pathlib.Path, *, name: str, spec: TemplateSpec, requires_python: str, source: str) -> None:
"""Print the confirmation, cd, local-run, deploy, and notes lines.

Uses :func:`click.echo` for consistency with the rest of the CLI; the
same commands are written into the project's ``README.md`` by
:func:`_render_readme` so stdout and on-disk docs agree.
"""
click.echo(f"\nProject {target.name}/ created.")
click.echo(f"Python requirement: {requires_python} (from {source})")
click.echo(f"To get started: cd {name}")
click.echo(f"To run locally: {_format_local_run(spec, name=name)}")
click.echo("To deploy: rsconnect deploy pyproject .")
Expand Down
Loading
Loading