Skip to content
Open
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- Reads deployment settings from `[tool.posit.connect]` in `pyproject.toml` and generates it in quickstart projects. The legacy `[tool.rsconnect]` name remains supported with a deprecation warning. [#976](https://github.com/posit-dev/rsconnect-python/pull/976)

### Changed

- Selects Python dependencies consistently for deploy and write-manifest: explicit and configured sources take precedence, followed by `uv.lock`, static `pyproject.toml` dependencies, and `requirements.txt`. Lockfiles are validated offline; generated requirements use `requirements-connect.txt` (or `requirements-connect-generated.txt` when needed) to preserve user-managed files.

### Removed

- **Breaking:** Removes support for running the CLI on Python 3.8–3.10. Installing on those versions resolves to 1.33.2, the last compatible release. Content can still target those versions: install the CLI in its own environment with `uv tool install rsconnect-python` ([Installation](index.md#installation)), and select the content Python with `--python` ([Choosing the content Python](deploying.md#choosing-the-content-python)) [#972](https://github.com/posit-dev/rsconnect-python/pull/972).
Expand Down
53 changes: 35 additions & 18 deletions docs/deploying.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,8 @@ rsconnect deploy notebook my-notebook.ipynb data.csv

#### Package Dependencies

If a `requirements.txt` file exists in the same directory as the notebook file, it will
be included in the bundle. It must specify the package dependencies needed to execute
the notebook. Posit Connect will reconstruct the Python environment using the
specified package list.
Dependency sources are selected using the same rules as for Python applications;
see [Python dependency sources](#python-dependency-sources).

With `--force-generate`, rsconnect-python determines package dependencies from the
content Python environment.
Expand Down Expand Up @@ -108,9 +106,8 @@ Install `nbconvert` in the selected Python environment to render static notebook
You can create a `manifest.json` file for a Jupyter Notebook, then use that manifest
in a later deployment. Use the `write-manifest` command to do this.

The `write-manifest` command also creates a `requirements.txt` file if it does
not already exist or if you specify `--force-generate`. It contains package
dependencies from the content Python environment.
When dependencies are generated, `write-manifest` writes a separate requirements
file alongside the manifest. See [Python dependency sources](#python-dependency-sources).

Here is an example of the `write-manifest` command:

Expand Down Expand Up @@ -209,10 +206,8 @@ Any directory that appears to be a Python virtual environment (by containing

#### Package Dependencies

If a `requirements.txt` file exists in the API/application directory, it will be
included in the bundle. It must specify the package dependencies needed to execute
the API or application. Posit Connect will reconstruct the Python environment using
the specified package list.
Dependency sources are selected using the same rules as for notebooks; see
[Python dependency sources](#python-dependency-sources).

With `--force-generate`, rsconnect-python determines package dependencies from the
content Python environment. Use `--python` to select an interpreter explicitly:
Expand Down Expand Up @@ -298,9 +293,8 @@ RENV_PATHS_LOCKFILE=/path/to/renv.lock rsconnect deploy api my-api/
You can create a `manifest.json` file for an API or application, then use that
manifest in a later deployment. Use the `write-manifest` command to do this.

The `write-manifest` command also creates a `requirements.txt` file if it does
not already exist or if you specify `--force-generate`. It contains package
dependencies from the content Python environment.
When dependencies are generated, `write-manifest` writes a separate requirements
file alongside the manifest. See [Python dependency sources](#python-dependency-sources).

Here is an example of the `write-manifest` command:

Expand Down Expand Up @@ -400,10 +394,33 @@ rsconnect deploy pyproject my_app/
```

The directory passed to `deploy pyproject` must contain `pyproject.toml`.
Dependencies follow the same resolution rules as the other deploy commands:
`[project.dependencies]` from `pyproject.toml` provides the dependency
snapshot, and `uv.lock` or `requirements.txt` may be supplied via
`--requirements-file` when a pinned environment is needed.
Dependencies follow the same resolution rules as the other deploy commands.

### Python dependency sources

Python deployment and manifest commands choose a dependency source in this order:
`--requirements-file`, `requirements_file` in `[tool.posit.connect]` (or the
legacy `[tool.rsconnect]` table), then `uv.lock`, `pyproject.toml`, and
`requirements.txt`. Automatic selection uses `pyproject.toml` only when
`[project].dependencies` is explicitly declared as a static list; an empty list
is valid. A selected source must be valid and readable: rsconnect-python will
not fall back to another source if it fails.

A selected `uv.lock` must be current with its companion `pyproject.toml`.
rsconnect-python validates and exports it offline without updating it. If the
lock is stale, run `uv lock` before retrying. If offline validation cannot
complete, ensure uv can find a Python interpreter compatible with the project's
`requires-python` (for example, run `uv python install <version>` while online)
and prepare the lock and uv cache before retrying.

Use `--force-generate` to snapshot the selected Python environment instead of
using a dependency source. It cannot be combined with `--requirements-file`.
When dependencies come from anything other than an unchanged requirements
file (`uv.lock`, `pyproject.toml`, or `--force-generate`), `write-manifest`
writes them to `requirements-connect.txt` and leaves user-managed files
unchanged. If that generated filename is already in use, it uses
`requirements-connect-generated.txt`. If both names contain user-managed files,
the command asks you to move one or select a different source.

### Options for All Types of Deployments

Expand Down
40 changes: 36 additions & 4 deletions rsconnect/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@

from . import metadata

from .environment import Environment, list_environment_dirs, is_environment_dir
from .environment import (
Environment,
list_environment_dirs,
is_environment_dir,
prepare_generated_requirements_filename,
)
from .environment_node import NodeEnvironment
from .environment_r import REnvironment
from .exception import RSConnectException
Expand Down Expand Up @@ -616,11 +621,12 @@ def write_manifest(
"""Create a manifest for source publishing the specified notebook.

The manifest will be written to `manifest.json` in the output directory..
A requirements.txt file will be created if one does not exist.
A generated requirements file will be created when dependencies are derived.

Returns the list of filenames written.
"""
_check_single_notebook_editables(environment)
prepare_generated_requirements_filename(environment, output_dir)
manifest_filename = "manifest.json"
manifest = make_source_manifest(
AppModes.JUPYTER_NOTEBOOK, environment, nb_name, None, image, env_management_py, env_management_r
Expand Down Expand Up @@ -710,6 +716,7 @@ def make_notebook_source_bundle(
if extra_files is None:
extra_files = []
base_dir = dirname(file)
prepare_generated_requirements_filename(environment, base_dir)
nb_name = basename(file)
config_dir = _resolved_config_dir()
_ensure_content_root_is_safe(base_dir, config_dir)
Expand Down Expand Up @@ -1145,6 +1152,7 @@ def make_api_manifest(
:param r_environment: optional R dependencies detected from renv.lock to add to the manifest.
:return: the manifest and a list of the files involved.
"""
prepare_generated_requirements_filename(environment, directory)
if is_environment_dir(directory):
excludes = list(excludes or []) + ["bin/", "lib/", "Lib/", "Scripts/", "Include/"]

Expand Down Expand Up @@ -1849,10 +1857,13 @@ def make_quarto_manifest(
:param r_environment: optional R dependencies detected from renv.lock to add to the manifest.
:return: the manifest and a list of the files involved.
"""
base_dir = file_or_directory
if not isdir(file_or_directory):
base_dir = dirname(file_or_directory)
if environment:
prepare_generated_requirements_filename(environment, base_dir)
extra_files = list(extra_files or [])

base_dir = file_or_directory
if isdir(file_or_directory):
# Directory as a Quarto project.
excludes = list(excludes or []) + [".quarto"]
Expand All @@ -1875,7 +1886,7 @@ def make_quarto_manifest(
t, _ = splitext(os.path.relpath(each, file_or_directory))
excludes = excludes + [t + ".html", t + "_files/**/*"]

# relevant files don't need to include requirements.txt file because it is
# relevant files don't need to include the requirements file because it is
# always added to the manifest (as a buffer) from the environment contents
if environment:
excludes.append(environment.filename)
Expand Down Expand Up @@ -2208,6 +2219,7 @@ def write_notebook_manifest_json(
if app_mode == AppModes.UNKNOWN:
raise RSConnectException('Could not determine the app mode from "%s"; please specify one.' % extension)

prepare_generated_requirements_filename(environment, directory)
manifest_data = make_source_manifest(
app_mode,
environment,
Expand Down Expand Up @@ -2307,6 +2319,7 @@ def create_voila_manifest(
raise RSConnectException(MULTI_NOTEBOOK_EXC_MSG)
_warn_on_ignored_entrypoint(entrypoint)
deploy_dir = entrypoint = abspath(path)
prepare_generated_requirements_filename(environment, deploy_dir)
extra_files = validate_extra_files(deploy_dir, extra_files, use_abspath=True)
excludes = list(excludes) if excludes else []
excludes.extend([environment.filename, "manifest.json"])
Expand Down Expand Up @@ -2535,6 +2548,14 @@ def write_nodejs_manifest_json(
write_manifest_json(manifest_path, manifest)


_GENERATED_SOURCE_DESCRIPTIONS = {
"pip_freeze": "snapshotted from the Python environment (--force-generate)",
"uv_lock": "exported from uv.lock",
"pyproject_toml": "generated from pyproject.toml [project].dependencies",
"derived_file": "normalized from the selected requirements file",
}


def write_environment_file(
environment: Environment,
directory: str,
Expand All @@ -2547,7 +2568,18 @@ def write_environment_file(
returned by the inspect_environment() function.
:param directory: the directory where the file should be written.
"""
if environment.source == "file":
return

prepare_generated_requirements_filename(environment, directory)
environment_file_path = join(directory, environment.filename)
if os.path.islink(environment_file_path):
raise RSConnectException(f"Cannot overwrite symlink at generated requirements path {environment_file_path}.")
description = _GENERATED_SOURCE_DESCRIPTIONS.get(environment.source, environment.source)
if exists(environment_file_path):
logger.info(f"Refreshing generated requirements at {environment_file_path} with requirements {description}.")
else:
logger.info(f"Writing {environment_file_path} with requirements {description}.")
# Write bytes so that the file matches the manifest checksum on all platforms.
# Text mode changes line endings and encoding on Windows.
with open(environment_file_path, "wb") as f:
Expand Down
48 changes: 48 additions & 0 deletions rsconnect/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
from .exception import RSConnectException
from .subprocesses.inspect_environment import EnvironmentData, MakeEnvironmentData as _MakeEnvironmentData

GENERATED_REQUIREMENTS_FILENAME = "requirements-connect.txt"
GENERATED_REQUIREMENTS_FALLBACK_FILENAME = "requirements-connect-generated.txt"
GENERATED_REQUIREMENTS_HEADER = "# Generated by rsconnect-python; refreshed on each manifest write.\n"
_GENERATED_REQUIREMENTS_MARKER = b"# Generated by rsconnect-python"


class PackageInstaller(StrEnum):
PIP = "pip"
Expand Down Expand Up @@ -151,6 +156,20 @@ def create_python_environment(
)
environment.python_version_requirement = python_version_requirement

if environment.source == "file" and requirements_file is not None:
source_path = pathlib.Path(directory) / requirements_file
try:
with source_path.open("r", encoding="utf-8", newline="") as source:
unchanged = source.read() == environment.contents
except (OSError, UnicodeError) as err:
raise RSConnectException(f"Cannot read requirements source {requirements_file}: {err}") from err
if not unchanged:
environment.source = "derived_file"

if environment.source != "file":
environment.filename = GENERATED_REQUIREMENTS_FILENAME
environment.contents = GENERATED_REQUIREMENTS_HEADER + environment.contents

if environment.source == "pip_freeze":
mismatch = pyproject.local_python_mismatch(python_version_requirement, environment.python)
if mismatch:
Expand Down Expand Up @@ -262,6 +281,35 @@ def _inspect_environment(
raise RSConnectException("Error constructing environment object") from e


def prepare_generated_requirements_filename(environment: Environment, directory: str) -> None:
"""Choose a generated requirements filename without claiming a user-managed file."""
if environment.source == "file":
return

for filename in (GENERATED_REQUIREMENTS_FILENAME, GENERATED_REQUIREMENTS_FALLBACK_FILENAME):
path = pathlib.Path(directory) / filename
if not os.path.lexists(path) or _is_generated_requirements_file(path):
environment.filename = filename
return

raise RSConnectException(
"Cannot write generated dependencies because both requirements-connect.txt and "
"requirements-connect-generated.txt already exist and are not generated by rsconnect-python. "
"Move one file or select a different requirements source."
)


def _is_generated_requirements_file(path: pathlib.Path) -> bool:
if path.is_symlink() or not path.is_file():
return False

try:
with path.open("rb") as file:
return file.readline().startswith(_GENERATED_REQUIREMENTS_MARKER)
except OSError:
return False


def _uv_bin() -> str:
try:
# conda-forge's uv package installs only the executable, not this module.
Expand Down
6 changes: 6 additions & 0 deletions rsconnect/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,11 @@ def set_in_feedback(self, value: bool):
self._in_feedback = value
self._have_feedback_output = False

def end_feedback_line(self) -> None:
if self._in_feedback and not self._have_feedback_output:
click.echo(err=self._quiet)
self._have_feedback_output = True

def set_quiet(self, value: bool):
self._quiet = value

Expand Down Expand Up @@ -188,6 +193,7 @@ def warn_user(message: str, fg: str = "yellow") -> None:
In quiet mode the warning is routed to stderr so that stdout stays
reserved for the content URL.
"""
logger.end_feedback_line()
click.secho(message, fg=fg, err=logger.quiet)


Expand Down
Loading
Loading