diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 31b11b79..491e6753 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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). diff --git a/docs/deploying.md b/docs/deploying.md index 03a15bfa..9d12eabb 100644 --- a/docs/deploying.md +++ b/docs/deploying.md @@ -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. @@ -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: @@ -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: @@ -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: @@ -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 ` 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 diff --git a/rsconnect/bundle.py b/rsconnect/bundle.py index 41222622..088a4ce8 100644 --- a/rsconnect/bundle.py +++ b/rsconnect/bundle.py @@ -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 @@ -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 @@ -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) @@ -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/"] @@ -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"] @@ -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) @@ -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, @@ -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"]) @@ -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, @@ -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: diff --git a/rsconnect/environment.py b/rsconnect/environment.py index 05081e42..bc42a452 100644 --- a/rsconnect/environment.py +++ b/rsconnect/environment.py @@ -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" @@ -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: @@ -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. diff --git a/rsconnect/log.py b/rsconnect/log.py index 2efe7b6b..03f0478c 100644 --- a/rsconnect/log.py +++ b/rsconnect/log.py @@ -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 @@ -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) diff --git a/rsconnect/main.py b/rsconnect/main.py index cb282f1e..c57ec29e 100644 --- a/rsconnect/main.py +++ b/rsconnect/main.py @@ -28,7 +28,7 @@ from rsconnect.certificates import read_certificate_file -from . import VERSION, api, validation +from . import VERSION, api, pyproject, validation from . import connect_cloud as connect_cloud_auth # aliased: `connect_cloud` is a CLI flag name from .version_check import BackgroundVersionCheck from .actions import ( @@ -112,7 +112,13 @@ ) from .environment_node import NodeEnvironment from .environment_r import REnvironment -from .environment import Environment, PackageInstaller, fake_module_file_from_directory, which_python +from .environment import ( + Environment, + PackageInstaller, + fake_module_file_from_directory, + prepare_generated_requirements_filename, + which_python, +) from .exception import RSConnectException from .git_metadata import detect_git_metadata from .json_web_token import ( @@ -2156,18 +2162,6 @@ def _warn_on_ignored_manifest(directory: str): warn_user(" Warning: the existing manifest.json file will not be used or considered.") -def _warn_on_ignored_requirements(directory: str, requirements_file_name: str): - """ - Checks for the existence of a file called manifest.json in the given directory. - If it's there, a warning noting that it will be ignored will be printed. - - :param directory: the directory to check in. - :param requirements_file_name: the name of the requirements file. - """ - if exists(join(directory, requirements_file_name)): - warn_user(" Warning: the existing %s file will not be used or considered." % requirements_file_name) - - # deploy notebook parameters that only affect a source bundle's Python or R environment. # A static notebook bundle contains only the rendered HTML, so they have no effect. _STATIC_NOTEBOOK_IGNORED_PARAMS = ( @@ -2248,13 +2242,13 @@ def _warn_on_options_ignored_by_static_notebook(ctx: click.Context, extra_files: "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", "-r", type=click.Path(dir_okay=False), - default="requirements.txt", + default=None, help=( "Path to requirements file listing the project dependencies. " "Any file compatible with requirements.txt format, uv.lock, or pyproject.toml is accepted, " @@ -2455,13 +2449,13 @@ def deploy_notebook( "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", "-r", type=click.Path(dir_okay=False), - default="requirements.txt", + default=None, help=( "Path to requirements file listing the project dependencies. " "Any file compatible with requirements.txt format, uv.lock, or pyproject.toml is accepted, " @@ -2797,6 +2791,7 @@ def deploy_bundle( @content_args @cloud_shinyapps_args @connect_cloud_args +@click.option("--force-generate", "-g", is_flag=True, help="Snapshot the selected Python environment.") @click.option( "--requirements-file", "-r", @@ -2804,9 +2799,7 @@ def deploy_bundle( default=None, help=( "Path to the requirements source, relative to the project directory. " - "Overrides ``[tool.posit.connect].requirements_file`` in pyproject.toml; " - "defaults to ``pyproject.toml`` (the project's declared dependencies). " - "Pass ``uv.lock`` for a fully resolved deploy, or any ``requirements.txt``-compatible file." + "Overrides the configured and automatically selected dependency source." ), ) @click.argument("directory", type=click.Path(exists=True, dir_okay=True, file_okay=False)) @@ -2843,6 +2836,7 @@ def deploy_pyproject( verbose: int, directory: str, requirements_file: str | None, + force_generate: bool, env_vars: dict[str, str], visibility: str | None, no_verify: bool, @@ -2862,9 +2856,7 @@ def quickstart_hint() -> str: # Only -t/--title overrides the pyproject title. The server nickname used # to be a fallback here, which made redeployments rename existing Connect # Cloud content after the nickname. - target = resolve_pyproject_deploy_target( - pyproject_path, requirements_file=requirements_file, title_override=title - ) + target = resolve_pyproject_deploy_target(pyproject_path, title_override=title) except UnsupportedAppModeError as err: raise RSConnectException(str(err)) from err except InvalidPyprojectConfigError as err: @@ -2877,7 +2869,8 @@ def quickstart_hint() -> str: app_mode = target.app_mode entrypoint = target.entrypoint effective_title = target.title - requirements_file = target.requirements_file + if force_generate and requirements_file is not None: + raise RSConnectException("--force-generate cannot be combined with --requirements-file.") extra_files: tuple[str, ...] = tuple() excludes: tuple[str, ...] = tuple() bundle_builder: Callable[..., Any] @@ -2890,14 +2883,19 @@ def quickstart_hint() -> str: # opts out, otherwise detection is driven by the lockfile's presence. r_environment = None if exclude_renv else REnvironment.create(directory) - if app_mode in (AppModes.STREAMLIT_APP, AppModes.PYTHON_SHINY, AppModes.PYTHON_FASTAPI, AppModes.PYTHON_API): - if app_mode == AppModes.PYTHON_SHINY: - entrypoint = resolve_shiny_express_entrypoint(entrypoint, directory) - environment = Environment.create_python_environment( + def inspect_python_environment() -> Environment: + return Environment.create_python_environment( directory, - requirements_file=requirements_file, + requirements_file=resolve_requirements_file( + directory, requirements_file, force_generate, warn_legacy=False + ), override_python_version=None, ) + + if app_mode in (AppModes.STREAMLIT_APP, AppModes.PYTHON_SHINY, AppModes.PYTHON_FASTAPI, AppModes.PYTHON_API): + if app_mode == AppModes.PYTHON_SHINY: + entrypoint = resolve_shiny_express_entrypoint(entrypoint, directory) + environment = inspect_python_environment() bundle_builder = make_api_bundle bundle_args = (directory, entrypoint, app_mode, environment, extra_files, excludes) bundle_kwargs = { @@ -2908,11 +2906,7 @@ def quickstart_hint() -> str: } elif app_mode == AppModes.JUPYTER_NOTEBOOK: # This is "jupyter-static" path = str(Path(directory) / entrypoint) - environment = Environment.create_python_environment( - directory, - requirements_file=requirements_file, - override_python_version=None, - ) + environment = inspect_python_environment() bundle_builder = make_notebook_source_bundle # Legacy app mode - no need to override the bundle builder default bundle_args = (path, environment, extra_files, False, False) @@ -2923,11 +2917,7 @@ def quickstart_hint() -> str: "r_environment": r_environment, } elif app_mode == AppModes.JUPYTER_VOILA: - environment = Environment.create_python_environment( - directory, - requirements_file=requirements_file, - override_python_version=None, - ) + environment = inspect_python_environment() bundle_builder = make_voila_bundle bundle_args = (directory, entrypoint, extra_files, excludes, True, environment) bundle_kwargs = { @@ -2949,11 +2939,7 @@ def quickstart_hint() -> str: environment = None if "jupyter" in engines: with cli_feedback("Inspecting Python environment"): - environment = Environment.create_python_environment( - directory, - requirements_file=requirements_file, - override_python_version=None, - ) + environment = inspect_python_environment() bundle_builder = create_quarto_deployment_bundle bundle_args = (path, extra_files, excludes, app_mode, inspect, environment) bundle_kwargs = { @@ -3108,7 +3094,7 @@ def deploy_git( short_help="Deploy Quarto content to Posit Connect or Posit Connect Cloud.", help=( "Deploy a Quarto document or project to Posit Connect or Posit Connect Cloud. Should the " - 'content use the Quarto Jupyter engine, an environment file ("requirements.txt") is created ' + 'content use the Quarto Jupyter engine, a generated environment file ("requirements-connect.txt") is created ' "and included in the deployment if one does not already exist." "\n\n" "FILE_OR_DIRECTORY is the path to a single-file Quarto document or the directory containing a Quarto project." @@ -3155,13 +3141,13 @@ def deploy_git( "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", "-r", type=click.Path(dir_okay=False), - default="requirements.txt", + default=None, help=( "Path to requirements file listing the project dependencies. " "Any file compatible with requirements.txt format, uv.lock, or pyproject.toml is accepted, " @@ -3555,17 +3541,39 @@ def deploy_html( ce.emit_content_url() -def resolve_requirements_file(directory: str, requirements_file: str | None, force_generate: bool) -> str | None: - """ - Determine which requirements file to use. - - Returns None when pip freeze should be used (force_generate=True), otherwise returns - the provided path or the default "requirements.txt". - """ +def resolve_requirements_file( + directory: str, requirements_file: str | None, force_generate: bool, warn_legacy: bool = True +) -> str | None: if force_generate: - _warn_on_ignored_requirements(directory, requirements_file or "requirements.txt") + if requirements_file is not None: + raise RSConnectException("--force-generate cannot be combined with --requirements-file.") return None - return requirements_file or "requirements.txt" + if requirements_file is not None: + return requirements_file + + project_path = Path(directory) / "pyproject.toml" + try: + if os.path.lexists(project_path): + config = pyproject.optional_deployment_config(project_path, warn_legacy=warn_legacy) + if "requirements_file" in config: + configured = config["requirements_file"] + if not isinstance(configured, str) or not configured.strip(): + raise RSConnectException("The configured requirements_file must be a non-empty string.") + return configured + if os.path.lexists(Path(directory) / "uv.lock"): + return "uv.lock" + if os.path.lexists(project_path): + project = tomllib.loads(project_path.read_text(encoding="utf-8-sig")).get("project", {}) + if isinstance(project, dict) and "dependencies" in project: + return "pyproject.toml" + except (OSError, tomllib.TOMLDecodeError, InvalidPyprojectConfigError) as err: + raise RSConnectException(f"Cannot read pyproject.toml: {err}") from err + if os.path.lexists(Path(directory) / "requirements.txt"): + return "requirements.txt" + raise RSConnectException( + "No Python dependency source found. Add uv.lock, static project dependencies, or requirements.txt, " + "specify --requirements-file, or use --force-generate." + ) def generate_deploy_python( @@ -3639,7 +3647,7 @@ def generate_deploy_python( "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", @@ -3997,8 +4005,7 @@ def write_manifest(): short_help="Create a manifest.json file for a Jupyter notebook.", help=( "Create a manifest.json file for a Jupyter notebook 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 notebook file." + "Derived dependencies are saved alongside the notebook." ), ) @click.option("--overwrite", "-o", is_flag=True, help="Overwrite manifest.json, if it exists.") @@ -4020,7 +4027,7 @@ def write_manifest(): "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", @@ -4079,8 +4086,8 @@ def write_manifest_notebook( if exists(manifest_path) and not overwrite: raise RSConnectException("manifest.json already exists. Use --overwrite to overwrite.") - requirements_file = resolve_requirements_file(base_dir, requirements_file, force_generate) with cli_feedback("Inspecting Python environment"): + requirements_file = resolve_requirements_file(base_dir, requirements_file, force_generate) environment = Environment.create_python_environment( base_dir, requirements_file=requirements_file, @@ -4090,7 +4097,9 @@ def write_manifest_notebook( ) r_environment = None if exclude_renv else REnvironment.create(base_dir) - generate_env = requirements_file is None + if environment.source != "file": + with cli_feedback("Creating %s" % environment.filename): + write_environment_file(environment, base_dir) with cli_feedback("Creating manifest.json"): environment_file_exists = write_notebook_manifest_json( file, @@ -4105,12 +4114,12 @@ def write_manifest_notebook( r_environment, ) - if environment_file_exists and not generate_env and environment.source != "uv_lock": + if environment_file_exists and environment.source == "file": click.secho( " Warning: %s already exists and will not be overwritten." % environment.filename, fg="yellow", ) - else: + elif environment.source == "file": with cli_feedback("Creating %s" % environment.filename): write_environment_file(environment, base_dir) @@ -4120,8 +4129,7 @@ def write_manifest_notebook( short_help="Create a manifest.json file for a Voila notebook.", help=( "Create a manifest.json file for a Voila notebook 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 notebook file." + "Derived dependencies are saved alongside the notebook." ), ) @click.option("--overwrite", "-o", is_flag=True, help="Overwrite manifest.json, if it exists.") @@ -4143,12 +4151,12 @@ def write_manifest_notebook( "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", "-r", - type=click.Path(exists=True, dir_okay=False), + type=click.Path(dir_okay=False), help=( "Path to requirements file listing the project dependencies. " "Any file compatible with requirements.txt format, uv.lock, or pyproject.toml is accepted, " @@ -4216,8 +4224,8 @@ def write_manifest_voila( if exists(manifest_path) and not overwrite: raise RSConnectException("manifest.json already exists. Use --overwrite to overwrite.") - requirements_file = resolve_requirements_file(base_dir, requirements_file, force_generate) with cli_feedback("Inspecting Python environment"): + requirements_file = resolve_requirements_file(base_dir, requirements_file, force_generate) environment = Environment.create_python_environment( base_dir, requirements_file=requirements_file, @@ -4229,7 +4237,7 @@ def write_manifest_voila( environment_file_exists = exists(join(base_dir, environment.filename)) generate_env = requirements_file is None - if environment_file_exists and not generate_env and environment.source != "uv_lock": + if environment_file_exists and environment.source == "file": click.secho( " Warning: %s already exists and will not be overwritten." % environment.filename, fg="yellow", @@ -4260,7 +4268,7 @@ def write_manifest_voila( help=( "Create a manifest.json file for a Quarto document or project for later " "deployment. Should the content use the Quarto Jupyter engine, " - 'an environment file ("requirements.txt") is created if one does ' + 'a generated environment file ("requirements-connect.txt") is created if one does ' "not already exist. All files are created in the same directory " "as the project." "\n\n" @@ -4302,7 +4310,7 @@ def write_manifest_voila( "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", @@ -4376,11 +4384,9 @@ def write_manifest_quarto( r_environment = None if exclude_renv else REnvironment.create(base_dir) environment = None - generate_env = False if "jupyter" in engines: - requirements_file = resolve_requirements_file(base_dir, requirements_file, force_generate) - generate_env = requirements_file is None with cli_feedback("Inspecting Python environment"): + requirements_file = resolve_requirements_file(base_dir, requirements_file, force_generate) environment = Environment.create_python_environment( base_dir, requirements_file=requirements_file, @@ -4390,7 +4396,7 @@ def write_manifest_quarto( ) environment_file_exists = exists(join(base_dir, environment.filename)) - if environment_file_exists and not generate_env and environment.source != "uv_lock": + if environment_file_exists and environment.source == "file": click.secho( " Warning: %s already exists and will not be overwritten." % environment.filename, fg="yellow", @@ -4421,13 +4427,14 @@ def write_manifest_quarto( "Create a manifest.json file for later deployment, for content described by a project's " "pyproject.toml. The given directory must contain a pyproject.toml with a [tool.posit.connect] " "table specifying app_mode and entrypoint. This will also write the environment file the " - 'manifest references (e.g. "requirements.txt"), regenerating it on each run unless it is ' - "itself the requirements source. Designed as the write-manifest partner for projects " + "manifest references, regenerating derived dependencies on each run. " + "Designed as the write-manifest partner for projects " "scaffolded by 'rsconnect quickstart'." ), no_args_is_help=True, ) @click.option("--overwrite", "-o", is_flag=True, help="Overwrite manifest.json, if it exists.") +@click.option("--force-generate", "-g", is_flag=True, help="Snapshot the selected Python environment.") @click.option( "--requirements-file", "-r", @@ -4435,9 +4442,7 @@ def write_manifest_quarto( default=None, help=( "Path to the requirements source, relative to the project directory. " - "Overrides ``[tool.posit.connect].requirements_file`` in pyproject.toml; " - "defaults to ``pyproject.toml`` (the project's declared dependencies). " - "Pass ``uv.lock`` for a fully resolved manifest, or any ``requirements.txt``-compatible file." + "Overrides the configured and automatically selected dependency source." ), ) @click.option("--verbose", "-v", "verbose", is_flag=True, help="Print detailed messages") @@ -4456,19 +4461,22 @@ def write_manifest_pyproject( ctx: click.Context, overwrite: bool, requirements_file: str | None, + force_generate: bool, verbose: int, exclude_renv: bool, directory: str, ): set_verbosity(verbose) output_params(ctx, locals().items()) + if force_generate and requirements_file is not None: + raise RSConnectException("--force-generate cannot be combined with --requirements-file.") def quickstart_hint() -> str: return "To create a new project with this section already populated, run: rsconnect quickstart --help" pyproject_path = Path(directory) / "pyproject.toml" try: - target = resolve_pyproject_deploy_target(pyproject_path, requirements_file=requirements_file) + target = resolve_pyproject_deploy_target(pyproject_path) except UnsupportedAppModeError as err: raise RSConnectException(str(err)) from err except InvalidPyprojectConfigError as err: @@ -4510,14 +4518,33 @@ def quickstart_hint() -> str: raise RSConnectException("manifest.json already exists. Use --overwrite to overwrite.") def inspect_python_environment() -> Environment: - # Deliberately not resolve_requirements_file: its default is requirements.txt, - # while pyproject projects default to pyproject.toml (deploy parity). with cli_feedback("Inspecting Python environment"): - return Environment.create_python_environment( + environment = Environment.create_python_environment( directory, - requirements_file=target.requirements_file, + requirements_file=resolve_requirements_file( + directory, requirements_file, force_generate, warn_legacy=False + ), override_python_version=None, ) + prepare_generated_requirements_filename(environment, str(manifest_dir)) + destination = manifest_dir / environment.filename + source = Path(directory) / environment.filename + if environment.source == "file" and destination.resolve() != source.resolve(): + try: + destination.resolve().relative_to(manifest_dir.resolve()) + except ValueError: + raise RSConnectException(f"Requirements destination {destination} is outside the manifest directory.") + if destination.is_symlink(): + raise RSConnectException(f"Cannot copy requirements to symlink {destination}.") + if destination.exists() and destination.read_bytes() != source.read_bytes(): + raise RSConnectException(f"Cannot overwrite the existing requirements file {destination}.") + destination.parent.mkdir(parents=True, exist_ok=True) + if not destination.exists(): + shutil.copyfile(source, destination) + elif environment.source != "file": + with cli_feedback("Creating %s" % environment.filename): + write_environment_file(environment, str(manifest_dir)) + return environment environment: Environment | None = None if app_mode in api_modes: @@ -4594,19 +4621,6 @@ def inspect_python_environment() -> Environment: r_environment=r_environment, ) - # The manifest references environment.filename (e.g. a requirements.txt - # generated from pyproject.toml's dependencies), so that file must exist - # next to manifest.json or deploying from the manifest fails. Regenerate it - # on every run so deployments pick up dependency changes, but never touch - # the requirements source itself: it is user-managed, and the inspector - # strips rsconnect lines from the contents it returns. Quarto with - # non-Jupyter engines has no environment. - if environment is not None: - requirements_source = (Path(directory) / target.requirements_file).resolve() - if requirements_source != (manifest_dir / environment.filename).resolve(): - with cli_feedback("Creating %s" % environment.filename): - write_environment_file(environment, str(manifest_dir)) - @write_manifest.command( name="tensorflow", @@ -4686,8 +4700,8 @@ def generate_write_manifest_python( name=alias, short_help=f"Create a manifest.json file for a {desc}.", help=( - 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 ' + f"Create a manifest.json file for a {desc} for later deployment. This may create " + "a generated dependency file. All files " "are created in the same directory as the API code." ), ) @@ -4725,7 +4739,7 @@ def generate_write_manifest_python( "--force-generate", "-g", is_flag=True, - help='Force generating "requirements.txt", even if it already exists.', + help="Snapshot dependencies from the selected Python environment.", ) @click.option( "--requirements-file", @@ -4773,7 +4787,8 @@ def manifest_writer( package_installer: PackageInstaller | None, requirements_file: str | None, ): - resolved_requirements_file = resolve_requirements_file(directory, requirements_file, force_generate) + with cli_feedback("Checking dependency source"): + resolved_requirements_file = resolve_requirements_file(directory, requirements_file, force_generate) _write_framework_manifest( ctx, overwrite, @@ -4959,6 +4974,9 @@ def _write_framework_manifest( with cli_feedback("Inspecting Shiny for Python app"): entrypoint = resolve_shiny_express_entrypoint(entrypoint, directory) + if environment.source != "file": + with cli_feedback("Creating %s" % environment.filename): + write_environment_file(environment, directory) with cli_feedback("Creating manifest.json"): environment_file_exists = write_api_manifest_json( directory, @@ -4973,13 +4991,12 @@ def _write_framework_manifest( r_environment, ) - generate_env = requirements_file is None - if environment_file_exists and not generate_env and environment.source != "uv_lock": + if environment_file_exists and environment.source == "file": click.secho( " Warning: %s already exists and will not be overwritten." % environment.filename, fg="yellow", ) - else: + elif environment.source == "file": with cli_feedback("Creating %s" % environment.filename): write_environment_file(environment, directory) diff --git a/rsconnect/pyproject.py b/rsconnect/pyproject.py index 40790893..b39d851a 100644 --- a/rsconnect/pyproject.py +++ b/rsconnect/pyproject.py @@ -209,7 +209,9 @@ 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) -> tuple[str, typing.Mapping[str, typing.Any]]: +def _read_deployment_config( + pyproject_file: pathlib.Path, required: bool = True +) -> tuple[str, typing.Mapping[str, typing.Any]]: content = pyproject_file.read_text(encoding="utf-8-sig") pyproject = tomllib.loads(content) tool = pyproject.get("tool") @@ -233,6 +235,8 @@ def _read_deployment_config(pyproject_file: pathlib.Path) -> tuple[str, typing.M table = "[tool.rsconnect]" config = tool["rsconnect"] else: + if not required: + return "", {} raise InvalidPyprojectConfigError( f"The [tool.posit.connect] section is missing; [tool.rsconnect] is also accepted. " f"Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" @@ -243,15 +247,26 @@ def _read_deployment_config(pyproject_file: pathlib.Path) -> tuple[str, typing.M f"{table} is not a TOML table. Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" ) config = typing.cast(typing.Mapping[str, typing.Any], config) - for field in ("app_mode", "entrypoint"): - value = config.get(field) - if not isinstance(value, str) or not value: - raise InvalidPyprojectConfigError( - f"The {table} field {field} must be a non-empty string. Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" - ) + if required: + for field in ("app_mode", "entrypoint"): + value = config.get(field) + if not isinstance(value, str) or not value: + raise InvalidPyprojectConfigError( + f"The {table} field {field} must be a non-empty string. " + f"Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" + ) return table, config +def optional_deployment_config( + pyproject_file: pathlib.Path, warn_legacy: bool = True +) -> typing.Mapping[str, typing.Any]: + table, config = _read_deployment_config(pyproject_file, required=False) + if warn_legacy and table == "[tool.rsconnect]": + logger.warning("[tool.rsconnect] is deprecated. Rename it to [tool.posit.connect].") + return config + + @dataclasses.dataclass(frozen=True) class PyprojectDeployTarget: """Deployment configuration resolved from pyproject.toml.""" @@ -278,8 +293,6 @@ def resolve_pyproject_deploy_target( a known app mode. :param pathlib.Path pyproject_file: path to the project's pyproject.toml. - :param typing.Optional[str] requirements_file: caller override for the - requirements source; wins over the configured ``requirements_file``. :param typing.Optional[str] title_override: fallback title used when the config declares none. """ @@ -293,12 +306,6 @@ def resolve_pyproject_deploy_target( if table == "[tool.rsconnect]": logger.warning("[tool.rsconnect] is deprecated. Rename it to [tool.posit.connect].") - # Requirements source precedence: caller override (the ``-r`` flag) > - # configured ``requirements_file`` > built-in default ``pyproject.toml`` - # (top-level deps; Connect resolves transitive). An explicit default keeps the - # inspector from falling back to a ``pip freeze`` of the caller's interpreter. - # Malformed TOML values (wrong type, missing file) are surfaced by the - # inspector / file existence check. return PyprojectDeployTarget( table=table, app_mode=app_mode, diff --git a/rsconnect/subprocesses/inspect_environment.py b/rsconnect/subprocesses/inspect_environment.py index c3a1685a..52736d4a 100644 --- a/rsconnect/subprocesses/inspect_environment.py +++ b/rsconnect/subprocesses/inspect_environment.py @@ -102,12 +102,18 @@ def detect_environment( elif os.path.basename(requirements_file) == "pyproject.toml": result = pyproject_dependencies(dirname, requirements_file) else: + if os.path.basename(requirements_file) in ("poetry.lock", "Pipfile.lock", "pdm.lock"): + raise EnvironmentException( + f"Unsupported dependency source {requirements_file}. " + "Provide a requirements file, pyproject.toml, or uv.lock instead." + ) file_result = output_file(dirname, requirements_file, "pip") if file_result is None: raise EnvironmentException( "The requirements file '%s' was not found in '%s'. " "Please create it or use --force-generate to use pip freeze." % (requirements_file, dirname) ) + validate_requirements(file_result["contents"], requirements_file, dirname) result = file_result if result is not None: @@ -189,6 +195,27 @@ def output_file(dirname: str, filename: str, package_manager: str): raise EnvironmentException("Error reading %s: %s" % (filename, str(exception))) +def validate_requirements(contents: str, filename: str, dirname: str) -> None: + """Check requirement specifiers while leaving pip options and paths to pip.""" + logical_lines = re.sub(r"\\\r?\n", " ", contents) + for number, raw_line in enumerate(logical_lines.splitlines(), 1): + line = re.split(r"\s+#", raw_line, maxsplit=1)[0].strip() + if not line or line.startswith(("#", "-", ".", "/", "file:", "http:", "https:", "git+", "hg+", "svn+", "bzr+")): + continue + if "${" in line or re.match(r"^[A-Za-z]:[\\/]", line) or os.path.exists(os.path.join(dirname, line)): + continue + requirement = re.split(r"\s+--(?:hash|config-settings)(?:=|\s)", line, maxsplit=1)[0] + if re.search(r"\.(?:whl|zip|tar\.gz|tar\.bz2|tgz)(?:\[.*\])?$", requirement): + continue + try: + Requirement(requirement) + except InvalidRequirement as err: + raise EnvironmentException( + f"Invalid requirement in {filename} near line {number}: {err}. " + "Fix the file or select another dependency source." + ) from err + + def pip_freeze(python: str, uv_path: str, pip_version: str | None, python_version: str): """Inspect the environment using `pip freeze`. @@ -268,6 +295,11 @@ def uv_export(dirname: str, lock_filename: str, uv_path: str = "uv"): if not os.path.exists(lock_path): raise EnvironmentException("uv.lock not found: %s" % lock_filename) + if not os.path.isfile(os.path.join(os.path.dirname(lock_path), "pyproject.toml")): + raise EnvironmentException( + f"Cannot validate {lock_filename}: its companion pyproject.toml is missing. " + "Restore the project metadata or choose another dependency source." + ) with tempfile.TemporaryDirectory() as tmpdir: output_path = os.path.join(tmpdir, "requirements.txt.lock") @@ -278,7 +310,7 @@ def uv_export(dirname: str, lock_filename: str, uv_path: str = "uv"): "export", "--format", "requirements-txt", - "--frozen", + "--locked", "--no-hashes", "--no-annotate", "--offline", @@ -290,15 +322,23 @@ def uv_export(dirname: str, lock_filename: str, uv_path: str = "uv"): output_path, ], cwd=os.path.dirname(lock_path), - stdout=sys.stderr, - stderr=sys.stderr, + capture_output=True, + text=True, check=False, ) except Exception as exception: raise EnvironmentException("Error during uv export: %s" % str(exception)) if result.returncode != 0: - raise EnvironmentException("Error during uv export: exited with code %d" % result.returncode) + detail = result.stderr.strip() + if "lockfile" in detail.lower() and "needs to be updated" in detail.lower(): + raise EnvironmentException(f"uv.lock is stale; run `uv lock` and retry. {detail}") + raise EnvironmentException( + f"Could not validate or export uv.lock offline: {detail}. " + "Ensure uv can find a Python interpreter compatible with the project's requires-python " + "(for example, install one with `uv python install ` while online), " + "and prepare the lock and uv cache before retrying." + ) with open(output_path, encoding="utf-8") as output_file: exported = output_file.read() @@ -341,10 +381,21 @@ def pyproject_dependencies(dirname: str, pyproject_filename: str): except Exception as exception: raise EnvironmentException(f"Error reading {pyproject_filename}: {exception}") - project = project_data or {} - dependencies: list[object] = project.get("dependencies", []) - if not isinstance(dependencies, list) or not all(isinstance(dep, str) for dep in dependencies): + if not isinstance(project_data, dict) or "dependencies" not in project_data: + raise EnvironmentException( + f"No static project.dependencies in {pyproject_filename}; declare a list or choose another source." + ) + raw_dependencies: object = project_data["dependencies"] + if not isinstance(raw_dependencies, list): + raise EnvironmentException(f"Invalid project.dependencies in {pyproject_filename}: expected a list of strings.") + dependencies = cast(list[object], raw_dependencies) + if not all(isinstance(dep, str) for dep in dependencies): raise EnvironmentException(f"Invalid project.dependencies in {pyproject_filename}: expected a list of strings.") + try: + for dependency in cast(list[str], dependencies): + Requirement(dependency) + except InvalidRequirement as err: + raise EnvironmentException(f"Invalid project.dependencies in {pyproject_filename}: {err}") from err requirements = filter_pip_freeze_output("\n".join(cast(list[str], dependencies))) if requirements and not requirements.endswith("\n"): diff --git a/tests/test_bundle.py b/tests/test_bundle.py index 13e406f2..25905a6a 100644 --- a/tests/test_bundle.py +++ b/tests/test_bundle.py @@ -57,7 +57,7 @@ ) from rsconnect.shiny_express import escape_to_var_name from rsconnect.environment_node import NodeEnvironment -from rsconnect.environment import Environment, PackageInstaller +from rsconnect.environment import GENERATED_REQUIREMENTS_FILENAME, Environment, PackageInstaller from rsconnect.exception import RSConnectException from rsconnect.models import AppModes @@ -407,19 +407,19 @@ def test_make_notebook_source_bundle2(self): "data.csv", "dummy.ipynb", "manifest.json", - "requirements.txt", + GENERATED_REQUIREMENTS_FILENAME, ], ) - reqs = tar.extractfile("requirements.txt").read() + reqs = tar.extractfile(GENERATED_REQUIREMENTS_FILENAME).read() # these are the dependencies declared in our setup.py self.assertIn(b"six", reqs) manifest = json.loads(tar.extractfile("manifest.json").read().decode("utf-8")) - # don't check requirements.txt since we don't know the checksum - del manifest["files"]["requirements.txt"] + # don't check generated requirements since we don't know the checksum + del manifest["files"][GENERATED_REQUIREMENTS_FILENAME] # also don't check locale value, just require it be present del manifest["locale"] @@ -445,7 +445,7 @@ def test_make_notebook_source_bundle2(self): "version": self.python_version(), "package_manager": { "name": "pip", - "package_file": "requirements.txt", + "package_file": GENERATED_REQUIREMENTS_FILENAME, }, }, "environment": { @@ -640,11 +640,11 @@ def test_make_quarto_source_bundle_from_simple_project(self): "_quarto.yml", "manifest.json", "myquarto.qmd", - "requirements.txt", + GENERATED_REQUIREMENTS_FILENAME, ], ) - reqs = tar.extractfile("requirements.txt").read() + reqs = tar.extractfile(GENERATED_REQUIREMENTS_FILENAME).read() self.assertIsNotNone(reqs) manifest = json.loads(tar.extractfile("manifest.json").read().decode("utf-8")) @@ -660,7 +660,7 @@ def test_make_quarto_source_bundle_from_simple_project(self): "version": self.python_version(), "package_manager": { "name": "pip", - "package_file": "requirements.txt", + "package_file": GENERATED_REQUIREMENTS_FILENAME, "version": mock.ANY, }, }, @@ -668,7 +668,7 @@ def test_make_quarto_source_bundle_from_simple_project(self): "files": { "_quarto.yml": {"checksum": mock.ANY}, "myquarto.qmd": {"checksum": mock.ANY}, - "requirements.txt": {"checksum": mock.ANY}, + GENERATED_REQUIREMENTS_FILENAME: {"checksum": mock.ANY}, }, }, ) @@ -750,11 +750,11 @@ def test_make_quarto_source_bundle_from_complex_project(self): "about.qmd", "index.qmd", "manifest.json", - "requirements.txt", + GENERATED_REQUIREMENTS_FILENAME, ], ) - reqs = tar.extractfile("requirements.txt").read() + reqs = tar.extractfile(GENERATED_REQUIREMENTS_FILENAME).read() self.assertIsNotNone(reqs) manifest = json.loads(tar.extractfile("manifest.json").read().decode("utf-8")) @@ -773,7 +773,7 @@ def test_make_quarto_source_bundle_from_complex_project(self): "version": self.python_version(), "package_manager": { "name": "pip", - "package_file": "requirements.txt", + "package_file": GENERATED_REQUIREMENTS_FILENAME, "version": mock.ANY, }, }, @@ -785,7 +785,7 @@ def test_make_quarto_source_bundle_from_complex_project(self): "_quarto.yml": {"checksum": mock.ANY}, "index.qmd": {"checksum": mock.ANY}, "about.qmd": {"checksum": mock.ANY}, - "requirements.txt": {"checksum": mock.ANY}, + GENERATED_REQUIREMENTS_FILENAME: {"checksum": mock.ANY}, }, }, ) @@ -4296,7 +4296,9 @@ def test_write_api_manifest_checksum_matches_environment_file(tmp_path: Path, wi write_environment_file(environment, str(tmp_path)) manifest = json.loads((tmp_path / "manifest.json").read_text()) - assert manifest["files"]["requirements.txt"]["checksum"] == file_checksum(tmp_path / "requirements.txt") + generated = tmp_path / GENERATED_REQUIREMENTS_FILENAME + assert manifest["files"][GENERATED_REQUIREMENTS_FILENAME]["checksum"] == file_checksum(generated) + assert generated.read_bytes() == to_bytes(environment.contents) def test_write_notebook_manifest_keeps_environment_file_bytes(tmp_path: Path, windows_text_mode: None): @@ -4304,7 +4306,7 @@ def test_write_notebook_manifest_keeps_environment_file_bytes(tmp_path: Path, wi write_manifest(".", "notebook.ipynb", environment, str(tmp_path)) - assert (tmp_path / "requirements.txt").read_bytes() == to_bytes(environment.contents) + assert (tmp_path / GENERATED_REQUIREMENTS_FILENAME).read_bytes() == to_bytes(environment.contents) def test_write_api_manifest_checksum_matches_crlf_requirements_file(tmp_path: Path): diff --git a/tests/test_connect_cloud.py b/tests/test_connect_cloud.py index dbb4bbd3..49121a70 100644 --- a/tests/test_connect_cloud.py +++ b/tests/test_connect_cloud.py @@ -3734,6 +3734,8 @@ def test_the_visibility_option_reaches_the_executor(self): notebook = os.path.join(project_dir, "notebook.ipynb") with open(notebook, "w") as f: f.write("{}") + with open(os.path.join(project_dir, "requirements.txt"), "w") as f: + f.write("") page = os.path.join(project_dir, "index.html") with open(page, "w") as f: f.write("") diff --git a/tests/test_dependency_selection.py b/tests/test_dependency_selection.py new file mode 100644 index 00000000..3375e3a1 --- /dev/null +++ b/tests/test_dependency_selection.py @@ -0,0 +1,335 @@ +import itertools +import json +import subprocess +import tarfile + +import pytest +import uv +from click.testing import CliRunner + +from rsconnect.bundle import file_checksum, make_manifest_bundle +from rsconnect.main import cli, resolve_requirements_file +from rsconnect.exception import RSConnectException + + +@pytest.mark.parametrize("requirements,project,lock", list(itertools.product([False, True], repeat=3))) +def test_source_precedence(tmp_path, requirements, project, lock): + if requirements: + (tmp_path / "requirements.txt").write_text("old==1\n") + if project: + (tmp_path / "pyproject.toml").write_text("[project]\ndependencies = []\n") + if lock: + (tmp_path / "uv.lock").write_text("") + expected = "uv.lock" if lock else "pyproject.toml" if project else "requirements.txt" if requirements else None + if expected: + assert resolve_requirements_file(str(tmp_path), None, False) == expected + else: + with pytest.raises(RSConnectException, match="No Python dependency source"): + resolve_requirements_file(str(tmp_path), None, False) + + +@pytest.mark.parametrize("project", ['[project]\nname = "example"\n', '[project]\ndynamic = ["dependencies"]\n']) +def test_non_static_project_is_skipped(tmp_path, project): + (tmp_path / "pyproject.toml").write_text(project) + (tmp_path / "requirements.txt").write_text("example\n") + assert resolve_requirements_file(str(tmp_path), None, False) == "requirements.txt" + + +def test_config_and_explicit_override(tmp_path): + (tmp_path / "pyproject.toml").write_text('[tool.posit.connect]\nrequirements_file = "custom.txt"\n') + (tmp_path / "uv.lock").touch() + assert resolve_requirements_file(str(tmp_path), None, False) == "custom.txt" + assert resolve_requirements_file(str(tmp_path), "other.txt", False) == "other.txt" + assert resolve_requirements_file(str(tmp_path), None, True) is None + with pytest.raises(RSConnectException, match="cannot be combined"): + resolve_requirements_file(str(tmp_path), "other.txt", True) + + +def test_generated_requirements_are_not_an_automatic_source(tmp_path): + (tmp_path / "requirements-connect.txt").write_text("# Generated by rsconnect-python\nflask\n") + + with pytest.raises(RSConnectException, match="No Python dependency source"): + resolve_requirements_file(str(tmp_path), None, False) + + +@pytest.mark.parametrize("command", ["api", "pyproject"]) +def test_manifest_preserves_requirements_when_writing_generated_dependencies(tmp_path, command): + (tmp_path / "app.py").write_text("app = object()\n") + source = tmp_path / "requirements.txt" + source.write_text("old==1\n") + project = tmp_path / "pyproject.toml" + project.write_text( + '[project]\ndependencies = ["flask==1"]\n[tool.posit.connect]\n' + 'app_mode = "python-api"\nentrypoint = "app:app"\n' + ) + runner = CliRunner() + for version in ("1", "2"): + project.write_text(project.read_text().replace("flask==1", f"flask=={version}")) + result = runner.invoke(cli, ["write-manifest", command, "--overwrite", str(tmp_path)]) + assert result.exit_code == 0, result.output + manifest = json.loads((tmp_path / "manifest.json").read_text()) + name = manifest["python"]["package_manager"]["package_file"] + generated = tmp_path / name + assert name == "requirements-connect.txt" + assert generated != source + assert source.read_text() == "old==1\n" + assert f"flask=={version}" in generated.read_text() + assert manifest["files"][name]["checksum"] == file_checksum(generated) + with ( + make_manifest_bundle(tmp_path / "manifest.json") as bundle, + tarfile.open(fileobj=bundle, mode="r:gz") as archive, + ): + assert f"flask=={version}" in archive.extractfile(name).read().decode() + + +@pytest.mark.parametrize("existing_generated_name", ["requirements-connect.txt"]) +def test_generated_requirements_use_collision_fallback(tmp_path, existing_generated_name): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / existing_generated_name).write_text("user-owned generated-name collision\n") + + result = CliRunner().invoke(cli, ["write-manifest", "api", "-g", str(tmp_path)]) + + assert result.exit_code == 0, result.output + manifest = json.loads((tmp_path / "manifest.json").read_text()) + assert manifest["python"]["package_manager"]["package_file"] == "requirements-connect-generated.txt" + assert (tmp_path / existing_generated_name).read_text() == "user-owned generated-name collision\n" + assert (tmp_path / "requirements-connect-generated.txt").read_text().startswith("# Generated by rsconnect-python") + + +def test_generated_requirements_fail_when_both_names_are_user_managed(tmp_path): + (tmp_path / "app.py").write_text("app = object()\n") + primary = tmp_path / "requirements-connect.txt" + fallback = tmp_path / "requirements-connect-generated.txt" + primary.write_text("primary user file\n") + fallback.write_text("fallback user file\n") + + result = CliRunner().invoke(cli, ["write-manifest", "api", "-g", str(tmp_path)]) + + assert result.exit_code == 1 + assert "both requirements-connect.txt and requirements-connect-generated.txt" in result.output + assert primary.read_text() == "primary user file\n" + assert fallback.read_text() == "fallback user file\n" + assert not (tmp_path / "manifest.json").exists() + + +@pytest.mark.parametrize("selection", ["automatic", "cli", "configured"]) +def test_fresh_and_stale_lock_offline(tmp_path, selection): + project = tmp_path / "pyproject.toml" + config = '\n[tool.posit.connect]\nrequirements_file = "uv.lock"\n' if selection == "configured" else "" + project.write_text('[project]\nname = "example"\nversion = "1.0"\ndependencies = []\n' + config) + subprocess.run([uv.find_uv_bin(), "lock", "--offline"], cwd=tmp_path, check=True, capture_output=True) + (tmp_path / "app.py").write_text("app = object()\n") + runner = CliRunner() + args = ["write-manifest", "api", "--overwrite"] + if selection == "cli": + args += ["-r", "uv.lock"] + result = runner.invoke(cli, [*args, str(tmp_path)]) + assert result.exit_code == 0, result.output + lock = (tmp_path / "uv.lock").read_bytes() + project.write_text(project.read_text().replace('version = "1.0"', 'version = "2.0"')) + result = runner.invoke(cli, [*args, str(tmp_path)]) + assert result.exit_code != 0 + assert "stale" in result.output.lower() + assert "uv lock" in result.output + assert (tmp_path / "uv.lock").read_bytes() == lock + + +@pytest.mark.parametrize("command", ["api", "pyproject"]) +def test_snapshot_conflicts_and_preserves_requirements(tmp_path, command): + (tmp_path / "app.py").write_text("app = object()\n") + project = tmp_path / "pyproject.toml" + project.write_text( + "[project]\ndependencies = []\n[tool.posit.connect]\n" + 'app_mode = "python-api"\nentrypoint = "app:app"\nrequirements_file = "missing.txt"\n' + ) + requirements = tmp_path / "requirements.txt" + requirements.write_text("user-owned\n") + runner = CliRunner() + result = runner.invoke(cli, ["write-manifest", command, "-g", "-r", "other.txt", str(tmp_path)]) + assert result.exit_code != 0 + assert "cannot be combined" in result.output + assert requirements.read_text() == "user-owned\n" + result = runner.invoke(cli, ["write-manifest", command, "-g", "--overwrite", str(tmp_path)]) + assert result.exit_code == 0, result.output + assert requirements.read_text() == "user-owned\n" + generated = tmp_path / "requirements-connect.txt" + assert generated.read_text().startswith("# Generated by rsconnect-python") + assert "user-owned" not in generated.read_text() + + +def test_missing_lock_companion_is_an_error(tmp_path): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "uv.lock").write_text("") + (tmp_path / "requirements.txt").write_text("flask\n") + result = CliRunner().invoke(cli, ["write-manifest", "api", str(tmp_path)]) + assert result.exit_code != 0 + assert "companion pyproject.toml is missing" in result.output + + +def test_broken_selected_lock_does_not_fall_back(tmp_path): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "requirements.txt").write_text("fallback==1\n") + try: + (tmp_path / "uv.lock").symlink_to("missing.lock") + except OSError: + pytest.skip("symlinks are unavailable") + result = CliRunner().invoke(cli, ["write-manifest", "api", str(tmp_path)]) + assert result.exit_code != 0 + assert "does not exist" in result.output + assert not (tmp_path / "manifest.json").exists() + + +def test_unsupported_lockfile_does_not_fall_back(tmp_path): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "requirements.txt").write_text("fallback==1\n") + (tmp_path / "poetry.lock").write_text("[metadata]\n") + result = CliRunner().invoke(cli, ["write-manifest", "api", "-r", "poetry.lock", str(tmp_path)]) + assert result.exit_code != 0 + assert "Unsupported dependency source" in result.output + assert not (tmp_path / "manifest.json").exists() + + +def test_malformed_requirements_does_not_fall_back(tmp_path): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "requirements.txt").write_text("invalid requirement = =\n") + result = CliRunner().invoke(cli, ["write-manifest", "api", str(tmp_path)]) + assert result.exit_code != 0 + assert "Invalid requirement in requirements.txt" in result.output + assert not (tmp_path / "manifest.json").exists() + + +def test_lock_validation_reports_missing_offline_metadata(tmp_path, monkeypatch): + project = tmp_path / "pyproject.toml" + project.write_text('[project]\nname = "example"\nversion = "1.0"\ndependencies = []\n') + subprocess.run([uv.find_uv_bin(), "lock", "--offline"], cwd=tmp_path, check=True, capture_output=True) + (tmp_path / "app.py").write_text("app = object()\n") + project.write_text( + project.read_text().replace("dependencies = []", 'dependencies = ["no-such-package-rsconnect-xyz==1"]') + ) + monkeypatch.setenv("UV_CACHE_DIR", str(tmp_path / "empty-cache")) + result = CliRunner().invoke(cli, ["write-manifest", "api", str(tmp_path)]) + assert result.exit_code != 0 + assert "validate or export uv.lock offline" in result.output + assert "uv cache" in result.output + assert "uv.lock is stale" not in result.output + + +def test_lock_validation_reports_missing_compatible_interpreter(tmp_path, monkeypatch): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "pyproject.toml").write_text( + '[project]\nname = "example"\nversion = "1.0"\nrequires-python = ">=9999"\ndependencies = []\n' + ) + (tmp_path / "uv.lock").write_text( + 'version = 1\nrequires-python = ">=9999"\n' + '[[package]]\nname = "example"\nversion = "1.0"\nsource = { virtual = "." }\n' + ) + monkeypatch.setenv("UV_PYTHON_INSTALL_DIR", str(tmp_path / "empty-pythons")) + monkeypatch.setenv("UV_PYTHON_PREFERENCE", "only-managed") + result = CliRunner().invoke(cli, ["write-manifest", "api", str(tmp_path)]) + assert result.exit_code != 0 + assert "No interpreter found" in result.output + assert "requires-python" in result.output + assert "uv python install " in result.output + assert "uv.lock is stale" not in result.output + + +@pytest.mark.parametrize("command", ["api", "pyproject"]) +def test_configured_source_and_cli_override(tmp_path, command): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "requirements.txt").write_text("automatic==1\n") + (tmp_path / "configured.txt").write_text("configured==2\n") + (tmp_path / "explicit.txt").write_text("explicit==3\n") + (tmp_path / "pyproject.toml").write_text( + '[project]\ndependencies = ["project==4"]\n[tool.posit.connect]\n' + 'app_mode = "python-api"\nentrypoint = "app:app"\nrequirements_file = "configured.txt"\n' + ) + runner = CliRunner() + for option, name in [([], "configured.txt"), (["-r", "explicit.txt"], "explicit.txt")]: + result = runner.invoke(cli, ["write-manifest", command, "--overwrite", *option, str(tmp_path)]) + assert result.exit_code == 0, result.output + manifest = json.loads((tmp_path / "manifest.json").read_text()) + assert manifest["python"]["package_manager"]["package_file"] == name + + +@pytest.mark.parametrize("dependencies", ['"wrong"', "[42]", '["not a valid requirement @"]']) +def test_invalid_selected_project_does_not_fall_back(tmp_path, dependencies): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "requirements.txt").write_text("fallback==1\n") + (tmp_path / "pyproject.toml").write_text(f"[project]\ndependencies = {dependencies}\n") + result = CliRunner().invoke(cli, ["write-manifest", "api", str(tmp_path)]) + assert result.exit_code != 0 + assert "Invalid project.dependencies" in result.output + assert not (tmp_path / "manifest.json").exists() + + +def test_framework_accepts_source_only_deployment_table(tmp_path): + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "pyproject.toml").write_text('[tool.posit.connect]\nrequirements_file = "custom.txt"\n') + (tmp_path / "custom.txt").write_text("configured==1\n") + runner = CliRunner() + framework = runner.invoke(cli, ["write-manifest", "api", str(tmp_path)]) + assert framework.exit_code == 0, framework.output + project = runner.invoke(cli, ["write-manifest", "pyproject", str(tmp_path)]) + assert project.exit_code != 0 + assert "app_mode" in project.output + + +def test_nested_manifest_copies_selected_source_without_overwriting(tmp_path): + notebook = tmp_path / "nested" / "notebook.ipynb" + notebook.parent.mkdir() + notebook.write_text('{"cells": [], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}') + (tmp_path / "pyproject.toml").write_text( + '[tool.posit.connect]\napp_mode = "jupyter-static"\n' + 'entrypoint = "nested/notebook.ipynb"\nrequirements_file = "requirements.txt"\n' + ) + source = tmp_path / "requirements.txt" + source.write_text("example==1\n") + runner = CliRunner() + result = runner.invoke(cli, ["write-manifest", "pyproject", str(tmp_path)]) + assert result.exit_code == 0, result.output + with make_manifest_bundle(notebook.parent / "manifest.json"): + pass + target = notebook.parent / "requirements.txt" + target.write_text("owned==2\n") + previous_manifest = (notebook.parent / "manifest.json").read_bytes() + result = runner.invoke(cli, ["write-manifest", "pyproject", "--overwrite", str(tmp_path)]) + assert result.exit_code != 0 + assert "Cannot overwrite" in result.output + assert target.read_text() == "owned==2\n" + assert source.read_text() == "example==1\n" + assert (notebook.parent / "manifest.json").read_bytes() == previous_manifest + + +@pytest.mark.parametrize("command", ["api", "notebook", "quarto", "pyproject"]) +@pytest.mark.parametrize( + "option,expected", [([], "configured.txt"), (["-r", "explicit.txt"], "explicit.txt"), (["-g"], None)] +) +def test_deploy_commands_apply_source_selection(tmp_path, monkeypatch, command, option, expected): + from rsconnect import main + + (tmp_path / "app.py").write_text("app = object()\n") + (tmp_path / "notebook.ipynb").write_text('{"cells": [], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}') + (tmp_path / "report.qmd").write_text("# Report\n") + (tmp_path / "uv.lock").write_text("") + (tmp_path / "pyproject.toml").write_text( + "[project]\ndependencies = []\n[tool.posit.connect]\n" + 'app_mode = "python-api"\nentrypoint = "app:app"\nrequirements_file = "configured.txt"\n' + ) + selected = [] + + def capture(cls, directory, **kwargs): + selected.append(kwargs["requirements_file"]) + raise RSConnectException("Inspection reached") + + monkeypatch.setattr(main.Environment, "create_python_environment", classmethod(capture)) + monkeypatch.setattr(main, "which_quarto", lambda *_: "quarto") + monkeypatch.setattr(main, "quarto_inspect", lambda *_: {"engines": ["jupyter"]}) + targets = { + "api": tmp_path, + "notebook": tmp_path / "notebook.ipynb", + "quarto": tmp_path / "report.qmd", + "pyproject": tmp_path, + } + result = CliRunner().invoke(cli, ["deploy", command, *option, str(targets[command]), "-s", "http://x", "-k", "k"]) + assert "Inspection reached" in result.output + assert selected == [expected] diff --git a/tests/test_deploy_pyproject.py b/tests/test_deploy_pyproject.py index abdd41b9..4dcbcdbd 100644 --- a/tests/test_deploy_pyproject.py +++ b/tests/test_deploy_pyproject.py @@ -345,6 +345,7 @@ def test_deploy_pyproject_dispatches_by_app_mode( [project] name = "hello_app" version = "0.0.1" + dependencies = [] [tool.{table}] app_mode = "{app_mode}" @@ -465,6 +466,7 @@ def test_deploy_pyproject_uses_title_from_tool_rsconnect( [project] name = "hello_app" version = "0.0.1" + dependencies = [] [tool.rsconnect] app_mode = "python-streamlit" @@ -596,20 +598,28 @@ def test_deploy_pyproject_defaults_requirements_to_pyproject_toml( assert captured["requirements_file"] == "pyproject.toml" -def test_deploy_pyproject_ignores_uv_lock_unless_requested( +def test_deploy_pyproject_prefers_uv_lock( runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch ): - """A ``uv.lock`` next to ``pyproject.toml`` does NOT auto-take over. - - Implicitly preferring a lockfile would silently deploy stale pins if the - user edited ``pyproject.toml`` without re-running ``uv lock``. Users who - want lockfile reproducibility must opt in with ``-r uv.lock``. - """ + """A lockfile takes precedence and is validated during inspection.""" captured = _capture_environment(monkeypatch) _write_pyproject(project_dir, _REQ_PYPROJECT) - (project_dir / "uv.lock").write_text("# placeholder; presence must not change the default\n") + (project_dir / "uv.lock").write_text("# placeholder\n") runner.invoke(cli, ["deploy", "pyproject", str(project_dir), "-s", "http://x", "-k", "k"]) - assert captured["requirements_file"] == "pyproject.toml" + assert captured["requirements_file"] == "uv.lock" + + +def test_deploy_pyproject_force_generate_bypasses_sources( + runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch +): + captured = _capture_environment(monkeypatch) + _write_pyproject(project_dir, _REQ_PYPROJECT + '\nrequirements_file = "missing.txt"\n') + runner.invoke(cli, ["deploy", "pyproject", "-g", str(project_dir), "-s", "http://x", "-k", "k"]) + assert captured["requirements_file"] is None + result = runner.invoke( + cli, ["deploy", "pyproject", "-g", "-r", "other.txt", str(project_dir), "-s", "http://x", "-k", "k"] + ) + assert "cannot be combined" in result.output def test_deploy_pyproject_requirements_file_flag_overrides_default( diff --git a/tests/test_environment.py b/tests/test_environment.py index f2c7bc1a..19a9795d 100644 --- a/tests/test_environment.py +++ b/tests/test_environment.py @@ -13,7 +13,12 @@ import rsconnect.environment from rsconnect.exception import RSConnectException -from rsconnect.environment import Environment, PackageInstaller, which_python +from rsconnect.environment import ( + GENERATED_REQUIREMENTS_FILENAME, + Environment, + PackageInstaller, + which_python, +) from rsconnect.subprocesses.inspect_environment import ( EnvironmentException, detect_environment, @@ -87,9 +92,9 @@ def test_requirements_override(self): project_dir, requirements_file=os.path.join("alt", "custom.txt") ) - assert result.filename.endswith("custom.txt") - assert result.contents == "foo==1.0\nbar>=2.0\n" - assert result.source == "file" + assert result.filename == GENERATED_REQUIREMENTS_FILENAME + assert result.contents.endswith("foo==1.0\nbar>=2.0\n") + assert result.source == "derived_file" def test_pip_freeze(self): result = Environment.create_python_environment(get_dir("pip2"), requirements_file=None) @@ -106,7 +111,7 @@ def test_pip_freeze(self): expected = Environment.from_dict( dict( contents=result.contents, - filename="requirements.txt", + filename=GENERATED_REQUIREMENTS_FILENAME, locale=result.locale, package_manager="pip", pip=result.pip, @@ -306,7 +311,7 @@ def test_requirements_file_filters_only_rsconnect_distribution(tmp_path: Path): env = Environment.create_python_environment(str(tmp_path)) - assert env.contents == "my-rsconnect-utils==0.1\r\ndemo\r\n# rsconnect note\r\n-e ./libs/local\r\n" + assert env.contents.endswith("my-rsconnect-utils==0.1\r\ndemo\r\n# rsconnect note\r\n-e ./libs/local\r\n") def test_requirements_file_rejects_editable_outside_bundle(tmp_path: Path): @@ -336,9 +341,8 @@ def target(path): env = Environment.create_python_environment(str(tmp_path)) - assert ( - env.contents - == "-e . # project\r\n-e file:./local%20package[extra]\r\n-e git+https://example.com/repo.git#egg=remote\r\n" + assert env.contents.endswith( + "-e . # project\r\n-e file:./local%20package[extra]\r\n-e git+https://example.com/repo.git#egg=remote\r\n" ) @@ -363,14 +367,14 @@ def test_uv_lock_export(tmp_path, monkeypatch, fallback, lock_location): project_dir = tmp_path / "project" project_dir.mkdir() (project_dir / "pyproject.toml").write_text( - "[project]\nname='demo'\nversion='0.0.0'\n" + "[project]\nname='demo'\nversion='0.0.0'\nrequires-python='>=3.8'\n" "dependencies=['aiofiles==24.1.0','annotated-doc==0.0.4','annotated-types==0.7.0']\n", encoding="utf-8", ) (project_dir / "uv.lock").write_text( """version = 1 revision = 3 -requires-python = ">=3.11.3" +requires-python = ">=3.8" [[package]] name = "aiofiles" @@ -431,6 +435,7 @@ def test_uv_lock_export(tmp_path, monkeypatch, fallback, lock_location): env_dir = project_dir / ".venv" subprocess.run([uv_path, "venv", "--python", sys.executable, str(env_dir)], check=True) python = env_dir / ("Scripts/python.exe" if os.name == "nt" else "bin/python") + monkeypatch.setenv("UV_PYTHON", str(python)) if fallback: monkeypatch.setenv("PATH", os.path.dirname(uv_path)) monkeypatch.setattr(uv, "find_uv_bin", missing_bundled_uv) @@ -445,7 +450,7 @@ def test_uv_lock_export(tmp_path, monkeypatch, fallback, lock_location): }[lock_location] env = Environment.create_python_environment(dirname, requirements_file=lock_file, python=str(python)) - assert env.filename == "requirements.txt.lock" + assert env.filename == GENERATED_REQUIREMENTS_FILENAME assert "aiofiles==24.1.0" in env.contents assert "annotated-doc==0.0.4" in env.contents assert "annotated-types==0.7.0" in env.contents @@ -579,12 +584,8 @@ def test_pyproject_dependencies_no_project_table(tmp_path): project_dir.mkdir() (project_dir / "pyproject.toml").write_text("[build-system]\nrequires = ['setuptools']\n", encoding="utf-8") - env = detect_environment(str(project_dir), requirements_file="pyproject.toml") - - assert env.filename == "requirements.txt" - assert env.source == "pyproject_toml" - # Header comment is present but no dependencies are listed. - assert all(line.startswith("#") or line == "" for line in env.contents.splitlines()) + with pytest.raises(EnvironmentException, match="No static project.dependencies"): + detect_environment(str(project_dir), requirements_file="pyproject.toml") class WhichPythonTestCase(TestCase): @@ -1190,6 +1191,7 @@ def test_force_generate_and_file_exists(self): """Force-generate ignores the existing requirements.txt and uses pip freeze.""" result = Environment.create_python_environment(get_dir("pip1"), requirements_file=None) assert result.source == "pip_freeze" + assert result.filename == GENERATED_REQUIREMENTS_FILENAME def test_force_generate_and_file_missing(self): """Force-generate works even without requirements.txt.""" diff --git a/tests/test_main.py b/tests/test_main.py index 606009c1..c0800959 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -550,7 +550,7 @@ def test_deploy_notebook_without_static_does_not_warn_on_static_ignored_options( mock.patch("rsconnect.main.RSConnectExecutor"), ): args = apply_common_args( - ["deploy", "notebook", str(notebook), str(data_file), "--no-verify", "-r", "requirements.txt", "-g"], + ["deploy", "notebook", str(notebook), str(data_file), "--no-verify", "-g"], server="http://fake_server", key="FAKE_API_KEY", ) @@ -2634,8 +2634,10 @@ def test_missing_requirements_reports_content_directory( result = CliRunner().invoke(cli, [*command, *requirements_option, path]) assert result.exit_code == 1 - expected_file = requirements_file or "requirements.txt" - assert f"The requirements file '{expected_file}' does not exist in '{expected_directory}'." in result.output + if requirements_file: + assert f"The requirements file '{requirements_file}' does not exist in '{expected_directory}'." in result.output + else: + assert "No Python dependency source found" in result.output @pytest.mark.parametrize( @@ -2669,7 +2671,7 @@ def test_document_commands_export_uv_lock_for_bare_and_relative_paths(tmp_path, else: assert result.exit_code == 0, result.output assert (tmp_path / "manifest.json").exists() - assert (tmp_path / "requirements.txt.lock").exists() + assert (tmp_path / "requirements-connect.txt").exists() @pytest.mark.parametrize("command", ["notebook", "voila", "quarto", "api", "pyproject"]) @@ -2685,13 +2687,6 @@ def test_write_manifest_requirements_overwrite(tmp_path, monkeypatch, command, r (tmp_path / "pyproject.toml").write_text(project) if generated: subprocess.run([sys.executable, "-m", "uv", "lock", "--offline"], check=True) - lock = tmp_path / "uv.lock" - lock.write_text( - lock.read_text() - + '\ndependencies = [{name = "example"}]\n' - + '\n[[package]]\nname = "example"\nversion = "1.0"\n' - + 'source = { registry = "https://pypi.org/simple" }\n' - ) else: supplied_contents = b"# Publisher requirements\r\nexample==1.0\r\n" (tmp_path / requirements_file).write_bytes(supplied_contents) @@ -2706,18 +2701,17 @@ def test_write_manifest_requirements_overwrite(tmp_path, monkeypatch, command, r assert result.exit_code == 0, result.output manifest_path = tmp_path / "manifest.json" original_manifest = manifest_path.read_bytes() - output = tmp_path / ("requirements.txt.lock" if generated else requirements_file) + output = tmp_path / ("requirements-connect.txt" if generated else requirements_file) original_contents = output.read_bytes() - if generated: - assert b"example==1.0" in original_contents - lock.write_text(lock.read_text().replace('version = "1.0"', 'version = "2.0"')) - result = runner.invoke(cli, args) assert result.exit_code != 0 assert "Use --overwrite" in result.output assert manifest_path.read_bytes() == original_manifest assert output.read_bytes() == original_contents + if generated: + output.write_bytes(original_contents + b"# stale generated content\n") + for _ in range(2): result = runner.invoke(cli, [*args, "--overwrite"]) assert result.exit_code == 0, result.output @@ -2727,7 +2721,7 @@ def test_write_manifest_requirements_overwrite(tmp_path, monkeypatch, command, r contents = (tmp_path / package_file).read_bytes() assert manifest["files"][package_file]["checksum"] == hashlib.md5(contents).hexdigest() if generated: - assert b"example==2.0" in contents + assert b"# stale generated content" not in contents else: assert contents == supplied_contents @@ -2823,7 +2817,7 @@ def test_malformed_pyproject_with_requirements_file(self, tmp_path): result = runner.invoke(cli, ["write-manifest", "api", str(tmp_path)]) assert result.exit_code == 1 - assert "Error: Error reading pyproject.toml:" in result.output + assert "Error: Cannot read pyproject.toml:" in result.output assert "line 1" in result.output assert "Traceback" not in result.output assert "Internal error" not in result.output @@ -2841,8 +2835,15 @@ def test_force_generate_requirements(self, tmp_path, existing_requirements): assert result.exit_code == 0, result.output manifest = json.loads((tmp_path / "manifest.json").read_text()) - assert requirements.read_text().startswith("# requirements.txt generated by rsconnect-python") - assert manifest["files"]["requirements.txt"]["checksum"] == file_checksum(requirements) + generated = tmp_path / "requirements-connect.txt" + assert generated.read_text().startswith("# Generated by rsconnect-python") + assert manifest["files"][generated.name]["checksum"] == file_checksum(generated) + assert "old-package" not in generated.read_text() + if existing_requirements: + assert requirements.read_text() == "old-package==1.0\n" + else: + assert not requirements.exists() + assert "Overwriting" not in result.output @pytest.mark.parametrize("path_kind", ["relative", "absolute", "normalized"]) def test_explicit_requirements_file(self, tmp_path, path_kind): @@ -2903,7 +2904,7 @@ def test_pyproject_requirements_file(self, tmp_path, dependencies): (tmp_path / "pyproject.toml").write_text(f"[project]\ndependencies = {dependencies}\n") result = CliRunner().invoke(cli, ["write-manifest", "api", "-r", "pyproject.toml", str(tmp_path)]) - requirements = tmp_path / "requirements.txt" + requirements = tmp_path / "requirements-connect.txt" if dependencies == "['flask']": assert result.exit_code == 0, result.output assert requirements.read_text().endswith("\nflask\n") diff --git a/tests/test_manifest_content_pythons.py b/tests/test_manifest_content_pythons.py index 929be8ad..90ce6f69 100644 --- a/tests/test_manifest_content_pythons.py +++ b/tests/test_manifest_content_pythons.py @@ -5,6 +5,7 @@ import pytest from click.testing import CliRunner +from rsconnect.environment import GENERATED_REQUIREMENTS_FILENAME from rsconnect.main import cli from scripts.content_python_versions import content_python_versions @@ -38,10 +39,9 @@ def test_manifest_uses_content_python_environment(version, tmp_path): assert result.exit_code == 0, result.output manifest = json.loads((project / "manifest.json").read_text()) assert manifest["python"]["version"] == expected_version - assert manifest["python"]["package_manager"]["package_file"] == "requirements.txt" - assert "idna==3.10" in (project / "requirements.txt").read_text().splitlines() + assert manifest["python"]["package_manager"]["package_file"] == GENERATED_REQUIREMENTS_FILENAME + assert "idna==3.10" in (project / GENERATED_REQUIREMENTS_FILENAME).read_text().splitlines() - (project / "requirements.txt").unlink() (project / "pyproject.toml").write_text('[project]\ndependencies = ["idna==3.10"]\n') result = CliRunner().invoke( cli, @@ -60,4 +60,5 @@ def test_manifest_uses_content_python_environment(version, tmp_path): assert result.exit_code == 0, result.output manifest = json.loads((project / "manifest.json").read_text()) assert manifest["python"]["version"] == expected_version - assert "idna==3.10" in (project / "requirements.txt").read_text().splitlines() + assert manifest["python"]["package_manager"]["package_file"] == GENERATED_REQUIREMENTS_FILENAME + assert "idna==3.10" in (project / GENERATED_REQUIREMENTS_FILENAME).read_text().splitlines() diff --git a/tests/test_write_manifest_pyproject.py b/tests/test_write_manifest_pyproject.py index 4a3d9635..62a61077 100644 --- a/tests/test_write_manifest_pyproject.py +++ b/tests/test_write_manifest_pyproject.py @@ -19,6 +19,7 @@ from click.testing import CliRunner from rsconnect.bundle import make_manifest_bundle +from rsconnect.environment import GENERATED_REQUIREMENTS_FILENAME, GENERATED_REQUIREMENTS_HEADER from rsconnect.main import cli @@ -51,9 +52,7 @@ def _read_manifest(project: pathlib.Path) -> dict[str, typing.Any]: def _fake_python_environment(monkeypatch: pytest.MonkeyPatch) -> dict[str, typing.Any]: """Replace subprocess-based environment inspection with a canned Environment. - Mirrors the real inspector's filename behavior: a pyproject.toml source - yields a generated virtual ``requirements.txt``, a ``uv.lock`` source yields - ``requirements.txt.lock``, and any other requirements file is read as-is. + Mirrors the real inspector's filename and source behavior. Captures the ``requirements_file`` handed to ``create_python_environment`` so tests can assert the requirements-source precedence without running pip. """ @@ -67,14 +66,17 @@ def fake_create(cls: typing.Any, directory: str, **kwargs: typing.Any) -> Enviro captured["directory"] = directory captured["requirements_file"] = requirements_file if requirements_file == "uv.lock": - filename = "requirements.txt.lock" - contents = "# requirements.txt.lock generated from uv.lock by rsconnect-python\nflask==2.0.0\n" + filename = GENERATED_REQUIREMENTS_FILENAME + contents = GENERATED_REQUIREMENTS_HEADER + "# generated from uv.lock\nflask==2.0.0\n" + source = "uv_lock" elif requirements_file in (None, "pyproject.toml"): - filename = "requirements.txt" - contents = "# requirements.txt generated from pyproject.toml by rsconnect-python\nflask\n" + filename = GENERATED_REQUIREMENTS_FILENAME + contents = GENERATED_REQUIREMENTS_HEADER + "# generated from pyproject.toml\nflask\n" + source = "pyproject_toml" else: filename = requirements_file contents = "flask\n" + source = "file" return Environment.from_dict( { "contents": contents, @@ -83,7 +85,7 @@ def fake_create(cls: typing.Any, directory: str, **kwargs: typing.Any) -> Enviro "package_manager": "pip", "pip": "23.0.1", "python": "3.11.0", - "source": "file", + "source": source, } ) @@ -169,10 +171,8 @@ def test_write_manifest_pyproject_writes_manifest_per_app_mode( manifest = _read_manifest(project_dir) assert manifest["metadata"]["appmode"] == app_mode assert manifest["metadata"]["entrypoint"] == expected_entrypoint - # The inspector turns pyproject.toml's dependencies into a virtual - # requirements.txt, which must also land on disk next to the manifest. - assert manifest["python"]["package_manager"]["package_file"] == "requirements.txt" - assert "generated from pyproject.toml" in (project_dir / "requirements.txt").read_text() + assert manifest["python"]["package_manager"]["package_file"] == GENERATED_REQUIREMENTS_FILENAME + assert "generated from pyproject.toml" in (project_dir / GENERATED_REQUIREMENTS_FILENAME).read_text() # Closed loop: deploying from the written manifest must find every file. with make_manifest_bundle(str(project_dir / "manifest.json")): pass @@ -212,7 +212,7 @@ def test_write_manifest_pyproject_quarto_jupyter_engine_inspects_python( manifest = _read_manifest(project_dir) assert manifest["metadata"]["appmode"] == "quarto-static" assert "python" in manifest - assert (project_dir / "requirements.txt").exists() + assert (project_dir / GENERATED_REQUIREMENTS_FILENAME).exists() def test_write_manifest_pyproject_shiny_express_entrypoint_is_rewritten( @@ -258,8 +258,7 @@ def test_write_manifest_pyproject_requirements_file_flag_overrides_default( result = runner.invoke(cli, ["write-manifest", "pyproject", "-r", "uv.lock", str(project_dir)]) assert result.exit_code == 0, result.output assert captured["requirements_file"] == "uv.lock" - # uv.lock is exported to a virtual requirements.txt.lock, which must land on disk. - assert (project_dir / "requirements.txt.lock").exists() + assert (project_dir / GENERATED_REQUIREMENTS_FILENAME).exists() with make_manifest_bundle(str(project_dir / "manifest.json")): pass @@ -307,7 +306,7 @@ def test_write_manifest_pyproject_writes_env_file_next_to_subdir_manifest( result = runner.invoke(cli, ["write-manifest", "pyproject", str(project_dir)]) assert result.exit_code == 0, result.output - assert (project_dir / "nb" / "requirements.txt").exists() + assert (project_dir / "nb" / GENERATED_REQUIREMENTS_FILENAME).exists() assert not (project_dir / "requirements.txt").exists() with make_manifest_bundle(str(project_dir / "nb" / "manifest.json")): pass @@ -319,24 +318,21 @@ def test_write_manifest_pyproject_regenerates_stale_env_file( """A stale generated env file is rewritten so deployments ship current dependencies.""" _fake_python_environment(monkeypatch) _write_pyproject(project_dir, _REQ_PYPROJECT) - (project_dir / "requirements.txt").write_text("stale-dependency==0.1\n") + generated = project_dir / GENERATED_REQUIREMENTS_FILENAME + generated.write_text(GENERATED_REQUIREMENTS_HEADER + "stale-dependency==0.1\n") result = runner.invoke(cli, ["write-manifest", "pyproject", str(project_dir)]) assert result.exit_code == 0, result.output - contents = (project_dir / "requirements.txt").read_text() + contents = generated.read_text() assert "stale-dependency" not in contents assert "flask" in contents -def test_write_manifest_pyproject_never_rewrites_explicit_requirements_source( +def test_write_manifest_pyproject_preserves_normalized_explicit_requirements_source( runner: CliRunner, project_dir: pathlib.Path ): - """When requirements.txt IS the configured source, it must stay untouched. - - Unmocked on purpose: the real inspector strips rsconnect lines from the - contents it returns, so a wrongful rewrite would corrupt the user's file. - """ + """The real inspector strips rsconnect lines into a generated file without changing the source.""" _write_pyproject( project_dir, """ @@ -358,7 +354,10 @@ def test_write_manifest_pyproject_never_rewrites_explicit_requirements_source( result = runner.invoke(cli, ["write-manifest", "pyproject", str(project_dir)]) assert result.exit_code == 0, result.output + generated = project_dir / GENERATED_REQUIREMENTS_FILENAME assert (project_dir / "requirements.txt").read_text() == source + assert "flask" in generated.read_text() + assert "rsconnect-python==1.25.0" not in generated.read_text() with make_manifest_bundle(str(project_dir / "manifest.json")): pass @@ -379,8 +378,8 @@ def test_write_manifest_pyproject_unmocked_end_to_end( assert result.exit_code == 0, result.output manifest = _read_manifest(project_dir) - assert manifest["python"]["package_manager"]["package_file"] == "requirements.txt" - assert "flask" in (project_dir / "requirements.txt").read_text() + assert manifest["python"]["package_manager"]["package_file"] == GENERATED_REQUIREMENTS_FILENAME + assert "flask" in (project_dir / GENERATED_REQUIREMENTS_FILENAME).read_text() with make_manifest_bundle(str(project_dir / "manifest.json")): pass