diff --git a/README.rst b/README.rst index 171e00b..0d6f385 100644 --- a/README.rst +++ b/README.rst @@ -25,6 +25,27 @@ and deploy's package clearing are skipped, even with ``--force-install``. With nonempty ``requires``, deploy retains its normal package-clearing behavior (including respecting ``--no-uninstall``). +Excluding files from deployment +------------------------------- + +Add ``deploy_exclude`` to your existing ``[tool.robotpy]`` section in +``pyproject.toml``:: + + deploy_exclude = ["tests/", "data/**", "!data/required.json"] + +Patterns use gitignore syntax relative to the project root, with forward slashes +on all platforms. Later patterns override earlier ones; ``!`` re-includes files, +provided their parent directories are not excluded. ``.gitignore`` files are not read. + +Defaults exclude names starting with a period, ``__pycache__/``, ``ctre_sim/``, +``logs/``, ``venv/``, and ``*.pyc``, ``*.whl``, ``*.ipk``, ``*.zip``, ``*.gz``, ``*.wpilog``. Your patterns +can override these defaults, for example:: + + deploy_exclude = ["!logs/", "!*.wpilog"] + +Exclusions apply to normal/local deploy and large-file warnings, including with +``--no-install``. Generated ``deploy.json`` metadata is always written. + Deployed Python version ----------------------- diff --git a/pyproject.toml b/pyproject.toml index c5c05ac..30666f9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,6 +25,7 @@ classifiers = [ dependencies = [ "packaging>=23.2", "paramiko", + "pathspec>=0.12.1", "pip>=26.2.2", "pynetconsole~=2.0.2", "robotpy-cli~=2027.0.1b1", diff --git a/robotpy_installer/cli_deploy.py b/robotpy_installer/cli_deploy.py index cbbaf74..4ae2abf 100644 --- a/robotpy_installer/cli_deploy.py +++ b/robotpy_installer/cli_deploy.py @@ -13,7 +13,9 @@ import threading import typing -from os.path import join, splitext +from os.path import join + +from pathspec import GitIgnoreSpec from . import pypackages, pyproject, robot_utils, sshcontroller from .installer import PipInstallError, PythonMissingError, RobotpyInstaller @@ -717,28 +719,44 @@ def _copy_to_tmpdir( self, tmp_dir: pathlib.Path, project_path: pathlib.Path, dry_run: bool = False ): upload_files = [] - ignore_exts = frozenset({".pyc", ".whl", ".ipk", ".zip", ".gz", ".wpilog"}) + # User patterns follow the defaults so negations can override them. + patterns = [ + ".*", + "__pycache__/", + "ctre_sim/", + "logs/", + "venv/", + "*.pyc", + "*.whl", + "*.ipk", + "*.zip", + "*.gz", + "*.wpilog", + ] + for pattern in pyproject.deploy_exclude_for_project(project_path): + if not pattern.endswith("\\ "): + pattern = pattern.rstrip() + # A trailing /** excludes contents, not the directory itself. + # Require a child segment to avoid pruning the parent directory. + if pattern.endswith("/**"): + pattern += "/*" + elif pattern.endswith("/**/"): + pattern += "*/" + patterns.append(pattern) + exclusions = GitIgnoreSpec.from_lines(patterns) - prefix_len = len(str(project_path)) + 1 for root, dirs, files in os.walk(project_path): - prefix = root[prefix_len:] + prefix = pathlib.Path(root).relative_to(project_path) if not dry_run: (tmp_dir / prefix).mkdir() - # skip .svn, .git, .hg, etc directories + # Prune excluded directories, as Git does when walking a tree. for d in dirs[:]: - if d.startswith(".") or d in ( - "__pycache__", - "ctre_sim", - "logs", - "venv", - ): + if exclusions.match_file((prefix / d).as_posix() + "/"): dirs.remove(d) - # skip .pyc files for filename in files: - r, ext = splitext(filename) - if ext in ignore_exts or r.startswith("."): + if exclusions.match_file((prefix / filename).as_posix()): continue fname = join(root, filename) diff --git a/robotpy_installer/pyproject.py b/robotpy_installer/pyproject.py index b6b1f8d..c2859cd 100644 --- a/robotpy_installer/pyproject.py +++ b/robotpy_installer/pyproject.py @@ -66,6 +66,9 @@ class RobotPyProjectToml: python_version: typing.Optional[str] = None + #: Additional gitignore-style deployment exclusions + deploy_exclude: typing.List[str] = dataclasses.field(default_factory=list) + @property def python_runtime(self) -> PythonRuntime: if self.robotpy_version is not None: @@ -480,6 +483,25 @@ def load( return _load(str(pyproject_path), data, base_path=project_path) +def _parse_deploy_exclude( + robotpy_data: typing.Dict[str, typing.Any], +) -> typing.List[str]: + patterns = robotpy_data.get("deploy_exclude", []) + if not isinstance(patterns, list) or not all(isinstance(p, str) for p in patterns): + raise PyprojectError("tool.robotpy.deploy_exclude must be a list of strings") + return patterns + + +def deploy_exclude_for_project(project_path: pathlib.Path) -> typing.List[str]: + """Read exclusions without requiring package settings (for --no-install).""" + path = toml_path(project_path) + if not path.exists(): + return [] + with path.open("rb") as fp: + data = tomli.load(fp) + return _parse_deploy_exclude(data.get("tool", {}).get("robotpy", {})) + + def runtime_for_project(project_path: pathlib.Path) -> PythonRuntime: """Select a runtime for standalone commands without creating a project.""" path = toml_path(project_path) @@ -608,6 +630,7 @@ def _load( return RobotPyProjectToml( robotpy_version=robotpy_version, python_version=python_version, + deploy_exclude=_parse_deploy_exclude(robotpy_data), components=components, requires=requires, ) diff --git a/tests/test_deploy_exclude.py b/tests/test_deploy_exclude.py new file mode 100644 index 0000000..93b200a --- /dev/null +++ b/tests/test_deploy_exclude.py @@ -0,0 +1,154 @@ +import argparse +import json +import pathlib + +import pytest + +from robotpy_installer import pyproject +from robotpy_installer.cli_deploy import Deploy, LocalDeploy + + +@pytest.mark.parametrize("deploy_cls", [Deploy, LocalDeploy]) +@pytest.mark.parametrize("dry_run", [False, True]) +@pytest.mark.parametrize( + "patterns, excluded", + [ + (["*.txt"], {"root.txt", "nested/root.txt"}), + (["/root.txt"], {"root.txt"}), + (["tests/"], {"tests/test_robot.py", "nested/tests/test_robot.py"}), + (["data/**", "!data/required.json"], {"data/extra.json"}), + (["data/** ", "!data/required.json"], {"data/extra.json"}), + (["nested/**/"], {"nested/tests/test_robot.py", "nested/deep/test_a.py"}), + (["data/", "!data/required.json"], {"data/extra.json", "data/required.json"}), + (["nested/**/test_?.py"], {"nested/deep/test_a.py"}), + (["# comment", "", "\\#notes"], {"#notes"}), + ([], set()), + ], +) +def test_deploy_exclusions(tmp_path, deploy_cls, dry_run, patterns, excluded): + source = tmp_path / "source" + source.mkdir() + config = '[tool.robotpy]\nrobotpy_version = "ignored"\n' + config += f"deploy_exclude = {json.dumps(patterns)}\n" + (source / "pyproject.toml").write_text(config) + files = { + "robot.py", + "root.txt", + "nested/root.txt", + "tests/test_robot.py", + "nested/tests/test_robot.py", + "data/extra.json", + "data/required.json", + "nested/deep/test_a.py", + "#notes", + } + defaults = {"logs/log.txt", "capture.wpilog", ".hidden", "venv/lib.py"} + for name in files | defaults: + path = source / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(name) + dest = tmp_path / "dest" + deploy = deploy_cls(argparse.ArgumentParser()) + uploaded = deploy._copy_to_tmpdir(dest, source, dry_run=dry_run) + expected = (files - excluded) | {"pyproject.toml"} + assert { + pathlib.Path(p).relative_to(source).as_posix() for p in uploaded + } == expected + if dry_run: + assert not dest.exists() + else: + assert { + p.relative_to(dest).as_posix() for p in dest.rglob("*") if p.is_file() + } == expected + for name in files - excluded: + assert (dest / name).read_text() == name + + +@pytest.mark.parametrize("value", ['"*.txt"', "42", '["*.txt", 1]', "{}"]) +def test_invalid_deploy_exclude(value): + with pytest.raises(pyproject.PyprojectError, match="deploy_exclude"): + pyproject.loads( + '[tool.robotpy]\nrobotpy_version="ignored"\ndeploy_exclude=' + value + ) + + +def test_no_pyproject(tmp_path): + source = tmp_path / "source" + source.mkdir() + (source / "robot.py").write_text("pass") + deploy = Deploy(argparse.ArgumentParser()) + assert deploy._copy_to_tmpdir(tmp_path / "dest", source) == [ + str(source / "robot.py") + ] + + +@pytest.mark.parametrize("deploy_cls", [Deploy, LocalDeploy]) +@pytest.mark.parametrize("dry_run", [False, True]) +@pytest.mark.parametrize( + "patterns, included", + [ + ([], set()), + ( + ["!/logs/", "!*.wpilog", "!/.hidden"], + {"logs/log.txt", "logs/keep.txt", "capture.wpilog", ".hidden"}, + ), + (["!logs/keep.txt"], set()), + (["!/logs/", "logs/*", "!logs/keep.txt"], {"logs/keep.txt"}), + (["!.config/", "!.config/keep.txt"], {".config/keep.txt"}), + (["!*.pyc", "nested/*.pyc"], {"cache.pyc"}), + ( + ["!venv/", "!ctre_sim/", "!__pycache__/"], + {"venv/lib.py", "ctre_sim/state", "__pycache__/other"}, + ), + ], +) +def test_override_default_exclusions(tmp_path, deploy_cls, dry_run, patterns, included): + source = tmp_path / "source" + source.mkdir() + (source / "pyproject.toml").write_text( + "[tool.robotpy]\ndeploy_exclude=" + json.dumps(patterns) + ) + files = { + "logs/log.txt", + "logs/keep.txt", + "capture.wpilog", + ".hidden", + ".config/keep.txt", + "cache.pyc", + "nested/cache.pyc", + "venv/lib.py", + "ctre_sim/state", + "__pycache__/other", + "package.whl", + "package.ipk", + "archive.zip", + "archive.gz", + "nested/.hidden", + "nested/logs/log.txt", + } + for name in files: + path = source / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(name) + dest = tmp_path / "dest" + uploaded = deploy_cls(argparse.ArgumentParser())._copy_to_tmpdir( + dest, source, dry_run + ) + expected = included | {"pyproject.toml"} + assert { + pathlib.Path(p).relative_to(source).as_posix() for p in uploaded + } == expected + if not dry_run: + assert { + p.relative_to(dest).as_posix() for p in dest.rglob("*") if p.is_file() + } == expected + + +def test_excluded_large_file_does_not_warn(tmp_path, capsys): + (tmp_path / "pyproject.toml").write_text( + '[tool.robotpy]\ndeploy_exclude=["big.dat"]' + ) + (tmp_path / "big.dat").write_bytes(b"x" * 250001) + deploy = Deploy(argparse.ArgumentParser()) + assert deploy._check_large_files(tmp_path) + assert "large files" not in capsys.readouterr().err