diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3646946 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,206 @@ +# Publish a tagged release to PyPI, the way sigrix-io/mullion does. Nothing else +# in this repository publishes, and nothing here runs on a branch: a release is +# a pushed `v*` tag, so publishing is an act with a name rather than a side +# effect of a merge. +# +# Trusted publishing (OIDC) rather than an API token: the runner trades a +# short-lived identity for the upload, so there is no long-lived secret in this +# repository to store, leak or rotate. PyPI must be told which repository, +# workflow file and environment it trusts: ftymoshchuk/pasteup, release.yml +# and `pypi` (see `environment:` below). +name: Release + +on: + push: + tags: ["v*"] + +# Read-only by default. Only the publish job widens this, and only to the one +# permission the OIDC exchange needs. +permissions: + contents: read + +# Deliberately not cancelled in progress, unlike tests.yml: a run stopped +# mid-upload can leave a release half-landed, and PyPI never accepts the same +# version number twice, not even after the file is deleted. +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + # Everything that can say no, said before anything leaves the runner. + build: + runs-on: ubuntu-latest + # A fork can push a tag to itself; it must not build the artifacts this + # repository's trusted publisher would then be asked to upload. + if: github.repository == 'ftymoshchuk/pasteup' + steps: + # The releases tests.yml runs on (its v5 and v6), pinned by commit: this + # runs once per release, the worst moment to meet an action's new major. + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: "3.13" + + - run: python -m pip install build twine + - run: python -m build + + # hatchling reads the version from src/pasteup/__init__.py; the tag is + # typed by hand, and nothing else makes the two agree. Tagging v0.2.0 + # without the bump would publish 0.1.0 under a tag saying otherwise, or + # fail at the upload with an error naming neither cause. + - name: The tag names the version that was built + run: | + set -euo pipefail + tag="${GITHUB_REF_NAME#v}" + # pasteup-0.1.0-py3-none-any.whl -> 0.1.0. A wheel filename uses "-" + # as its separator, so a PEP 440 version never contains one. + built="$(basename "$(ls dist/*.whl)" | cut -d- -f2)" + echo "tag=${tag} built=${built}" + if [ "${tag}" != "${built}" ]; then + echo "::error::tag ${GITHUB_REF_NAME} does not name the packaged version ${built}. Bump __version__ in src/pasteup/__init__.py, or delete the tag and retag." + exit 1 + fi + + # Keep a Changelog puts the version in a heading, so both checks are + # exact. The second catches entries still filed under [Unreleased]: they + # are on the commit being tagged, so they ship while the changelog says + # they did not. + - name: The changelog names this version, and nothing is left unreleased + run: | + set -euo pipefail + export VERSION="${GITHUB_REF_NAME#v}" + python - <<'PY' + import os + import pathlib + import re + + version = os.environ["VERSION"] + text = pathlib.Path("CHANGELOG.md").read_text() + + + def fail(message: str) -> None: + # stdout, not stderr: that is where GitHub reads ::error:: from. + print(message) + raise SystemExit(1) + + + if f"## [{version}]" not in text: + fail( + f"::error::CHANGELOG.md has no '## [{version}]' heading. Add it, or " + "move the Unreleased entries under it, before tagging." + ) + + section = re.search( + r"^##\s*\[Unreleased\]\s*$(.*?)(?=^##\s|\Z)", + text, + re.MULTILINE | re.DOTALL, + ) + if section: + leftover = [ + line + for line in section.group(1).splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + if leftover: + fail( + f"::error::CHANGELOG.md still files {len(leftover)} line(s) under " + f"[Unreleased], starting {leftover[0].strip()[:60]!r}. They ship in " + f"{version}: move them under '## [{version}]' before tagging." + ) + PY + + # A README that renders on GitHub but not on PyPI is otherwise found at + # the moment of publishing. + - run: python -m twine check --strict dist/* + + # The preview-video tests encode real files; without ffmpeg they skip. + - name: Install ffmpeg + run: sudo apt-get update && sudo apt-get install --yes --no-install-recommends ffmpeg + + # tests.yml proves the source tree; this proves the artifact, the only + # thing that matters once its bytes are immutable on PyPI. A template or + # font missing from the wheel fails here. + - name: The built wheel installs and passes the suite + run: | + set -euo pipefail + python -m venv /tmp/releasecheck + wheel="$(ls dist/*.whl)" + /tmp/releasecheck/bin/python -m pip install --quiet "${wheel}[dev]" + # The src layout leaves nothing in the checkout that `import pasteup` + # could find, so the suite can only be testing the wheel. Asserted + # rather than assumed. + /tmp/releasecheck/bin/python -c "import pasteup; assert 'site-packages' in pasteup.__file__, pasteup.__file__" + /tmp/releasecheck/bin/pasteup --version + /tmp/releasecheck/bin/python -m pytest -q tests/ + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist + path: dist/ + if-no-files-found: error + + # Separate from the build, so a failure above cannot half-publish: this job + # starts only when every check passed, and builds nothing itself. + publish: + needs: build + runs-on: ubuntu-latest + environment: + # PyPI's trusted publisher names this environment alongside the + # repository and the workflow filename; all three must match what is set + # up there. It is also where to add a required reviewer, should a release + # ever need a second pair of eyes. + name: pypi + url: https://pypi.org/p/pasteup + permissions: + # The only elevated permission in this file: it mints the OIDC token PyPI + # exchanges for an upload, and lets the action attach attestations. + id-token: write + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist + path: dist/ + + # Pinned to the commit, not the tag: a tag can be moved by whoever owns + # the action, and this is the one step here holding a credential. + - uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + + # An upload that succeeded is not yet a package anyone can install. Install + # it by name from PyPI, the way a user would, and check it is this version + # and carries the app's files. + verify: + needs: publish + runs-on: ubuntu-latest + steps: + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: "3.13" + + - name: The published package installs by name and runs + run: | + set -euo pipefail + version="${GITHUB_REF_NAME#v}" + python -m venv /tmp/published + # A fresh upload can take a few minutes to be served everywhere. + for attempt in $(seq 1 20); do + if /tmp/published/bin/python -m pip install --quiet --no-cache-dir "pasteup==${version}"; then + break + fi + if [ "${attempt}" = 20 ]; then + echo "::error::pasteup ${version} still cannot be installed from PyPI after 20 attempts." + exit 1 + fi + sleep 15 + done + cd /tmp + test "$(/tmp/published/bin/pasteup --version)" = "pasteup ${version}" + /tmp/published/bin/python - <<'PY' + import pathlib + + import pasteup + + root = pathlib.Path(pasteup.__file__).parent + for asset in ("templates/index.html", "static/js/app.js", "static/fonts/caveat-latin-700.woff2"): + assert (root / asset).is_file(), f"{asset} did not ship" + print("pasteup", pasteup.__version__, "installs from PyPI with its files") + PY diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 205b6c2..ad7afd3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -19,7 +19,7 @@ jobs: fail-fast: false matrix: # 3.11 is the floor: mullion and the app's StrEnum use need it. - python-version: ["3.11", "3.13"] + python-version: ["3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v5 @@ -45,12 +45,55 @@ jobs: - name: Test run: pytest -rs + # The package as users get it from PyPI: build it, check the README renders + # there, and install the wheel where the checkout cannot stand in for it. + # The release workflow repeats this; here a slip shows up on the pull request + # instead of at release time. + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + + - run: python -m pip install build twine + - run: python -m build + - run: python -m twine check --strict dist/* + + - name: The built wheel installs, runs and carries the app's files + run: | + set -euo pipefail + python -m venv /tmp/wheelcheck + /tmp/wheelcheck/bin/python -m pip install --quiet dist/*.whl + cd /tmp + /tmp/wheelcheck/bin/pasteup --version + /tmp/wheelcheck/bin/python - <<'PY' + import pathlib + + import pasteup + + root = pathlib.Path(pasteup.__file__).parent + assert "site-packages" in str(root), root + for asset in ( + "templates/index.html", + "static/js/app.js", + "static/css/styles.css", + "static/favicon.svg", + "static/fonts/caveat-latin-700.woff2", + "static/fonts/patrick-hand-latin-400.woff2", + ): + assert (root / asset).is_file(), f"{asset} did not ship" + print("wheel ok:", pasteup.__version__) + PY + # The aggregate gate, as in sigrix-io/mullion: the one check the branch # ruleset requires on main, so changing the matrix or adding a job does not # mean editing the ruleset to match. ci-passed: if: always() - needs: [test] + needs: [test, build] runs-on: ubuntu-latest steps: - name: Every job succeeded diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..2fd4a71 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,33 @@ +# Changelog + +All notable changes to Pasteup are recorded here. The format follows +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow +[Semantic Versioning](https://semver.org/spec/v2.0.0.html). While Pasteup is +0.x, a minor version may change behaviour. + +## [Unreleased] + +## [0.1.0] - 2026-10-16 + +The first release on PyPI. + +### Added +- Preview sheets: every image of a bundle in 4x3 grids on a white page, as PNG + or JPG, sized in pixels, inches or millimetres, with the DPI stamped into + the file. A part-filled last page is optional. +- Cover collages in three layouts, optionally limited to images you name. +- Preview videos: an MP4 slideshow of the sheets, as long as you ask, with a + crossfade or flip between them. Needs ffmpeg. +- Batch mode: every bundle folder inside a folder, listed, checked and made in + one go. +- Image clean-up: transparent PNGs land on white, phone photos are turned + upright, and near-white backgrounds can be made pure white or transparent. +- A hand-drawn browser interface in three steps, with each result beside the + step that made it. It runs entirely on your computer and needs no internet + connection. +- The `pasteup` command opens the app in your browser, reuses a copy that is + already running and moves to a free port when another program has 8000. + `pasteup --shortcut` makes a double-click launcher. + +[Unreleased]: https://github.com/ftymoshchuk/pasteup/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/ftymoshchuk/pasteup/releases/tag/v0.1.0 diff --git a/README.md b/README.md index bf0fc4a..48315ff 100644 --- a/README.md +++ b/README.md @@ -19,26 +19,43 @@ publishing: cut out by hand and pasted onto a layout board. - **Batch mode:** process every bundle folder under a parent folder in one go. ## Install -Requires Python 3.11 or newer. The preview video also needs -[ffmpeg](https://ffmpeg.org/) on `PATH`. +You need Python 3.11 or newer. Preview videos also need +[ffmpeg](https://ffmpeg.org/download.html); everything else works without it. + +Install Pasteup as a command of its own with [pipx](https://pipx.pypa.io) or +[uv](https://docs.astral.sh/uv/), with no virtualenv to manage: ```bash -git clone https://github.com/ftymoshchuk/pasteup.git -cd pasteup -python -m venv .venv -source .venv/bin/activate -pip install . +pipx install pasteup +# or +uv tool install pasteup ``` +To update it later: `pipx upgrade pasteup` or `uv tool upgrade pasteup`. To try +it without installing anything: `uvx pasteup`. + +For changes not released yet, install from GitHub instead: +`pipx install git+https://github.com/ftymoshchuk/pasteup.git`. + ## Run ```bash pasteup ``` -Then open `http://127.0.0.1:8000/` (API docs: `http://127.0.0.1:8000/docs`). -`pasteup --help` lists the options, and `python -m pasteup` works too. +Pasteup starts and opens in your browser. Keep its window open while you use +it, and press Ctrl+C there to stop it. Running `pasteup` again while it runs +just opens it again, and if another program has port 8000, Pasteup takes the +next free port and says which. + +**To start it with a double-click,** run `pasteup --shortcut` once. It puts a +launcher on your desktop (`Pasteup.command` on macOS, `Pasteup.bat` on +Windows) or in your applications menu on Linux. Run it again if you reinstall +Pasteup somewhere else. + +`pasteup --help` lists the options, among them `--no-browser` and `--port`; +`python -m pasteup` works too. The API docs are at `/docs`. Pasteup reads and writes files at the paths you give it and has no login, so -keep it on `127.0.0.1` (the default). See [SECURITY.md](SECURITY.md). +keep it on `127.0.0.1` (the default). See [SECURITY.md](https://github.com/ftymoshchuk/pasteup/blob/main/SECURITY.md). ### Optional environment variables - `PASTEUP_INPUT_FOLDER`: prefills the input-folder field, e.g. @@ -49,25 +66,43 @@ keep it on `127.0.0.1` (the default). See [SECURITY.md](SECURITY.md). ## Development ```bash +git clone https://github.com/ftymoshchuk/pasteup.git +cd pasteup +python -m venv .venv +source .venv/bin/activate pip install -e ".[dev]" ruff check . pytest ``` -CI runs the same on Python 3.11 and 3.13, against a regular install of the -package and with ffmpeg present, so the preview-video tests encode real files. -Its `ci-passed` job succeeds only when every other job does, and is the one -check `main` requires. +CI runs the same on Python 3.11, 3.12 and 3.13, against a regular install of +the package and with ffmpeg present, so the preview-video tests encode real +files. It also builds the package, checks the README renders on PyPI and +installs the wheel. Its `ci-passed` job succeeds only when every other job +does, and is the one check `main` requires. `scripts/protect-repo.sh` applies the repository's branch ruleset and security settings through the GitHub CLI; it needs `gh` signed in as a repository admin. +### Releasing +1. Bump `__version__` in `src/pasteup/__init__.py` and move the + `[Unreleased]` entries in `CHANGELOG.md` under a heading for that version. +2. Merge that through a pull request. +3. Tag the merge commit and push the tag, e.g. + `git tag v0.2.0 origin/main && git push origin v0.2.0`. + +The `Release` workflow then builds the package, refuses a tag that does not +match the built version or a changelog that does not name it, runs the test +suite against the built wheel, publishes to PyPI by trusted publishing (no +token is stored anywhere), and installs the result back from PyPI to check it. +PyPI trusts `release.yml` running in this repository's `pypi` environment. + Project layout: - `src/pasteup/main.py`: the FastAPI app - `src/pasteup/routes/`: the page and the `/api/jobs` endpoints - `src/pasteup/services/`: scanning, page composition, collages, export, video - `src/pasteup/models/`: request and response schemas - `src/pasteup/templates/` and `src/pasteup/static/`: the UI -- `src/pasteup/cli.py`: the `pasteup` command +- `src/pasteup/cli.py`: the `pasteup` command; `shortcut.py` makes its launchers - `tests/` --- @@ -116,7 +151,7 @@ Health check endpoint. **Response** ```json -{"status": "ok"} +{"status": "ok", "app": "pasteup", "version": "0.1.0"} ``` ### `POST /api/jobs/scan-folder` @@ -400,11 +435,11 @@ exporter, so a bad mullion upgrade still fails here. --- ## License -Apache License 2.0, see [LICENSE](LICENSE). Security reports: see -[SECURITY.md](SECURITY.md). +Apache License 2.0, see [LICENSE](https://github.com/ftymoshchuk/pasteup/blob/main/LICENSE). Security reports: +see [SECURITY.md](https://github.com/ftymoshchuk/pasteup/blob/main/SECURITY.md). The handwriting fonts the app ships with, [Caveat](https://fonts.google.com/specimen/Caveat) and [Patrick Hand](https://fonts.google.com/specimen/Patrick+Hand), are under the SIL Open Font License 1.1; their licence texts are in -[src/pasteup/static/fonts](src/pasteup/static/fonts). They are bundled rather +[src/pasteup/static/fonts](https://github.com/ftymoshchuk/pasteup/tree/main/src/pasteup/static/fonts). They are bundled rather than fetched, so the app needs no internet connection. diff --git a/pyproject.toml b/pyproject.toml index 349d462..6ac740c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,9 +7,11 @@ name = "pasteup" dynamic = ["version"] description = "Turn a folder of clip art into listing images: preview sheets, cover collages and preview videos." readme = "README.md" -license = "Apache-2.0" -license-files = ["LICENSE"] +# The code is Apache-2.0; the bundled handwriting fonts are OFL-1.1. +license = "Apache-2.0 AND OFL-1.1" +license-files = ["LICENSE", "src/pasteup/static/fonts/OFL-*.txt"] requires-python = ">=3.11" +keywords = ["clip art", "etsy", "listing images", "contact sheet", "collage"] # Compatible-release pins: bug-fix releases flow in, while anything that may # change behaviour (a new minor of a 0.x package, a new major elsewhere) is a # deliberate bump. mullion is pre-1.0, so its minor is pinned too. @@ -23,9 +25,15 @@ dependencies = [ ] classifiers = [ "Development Status :: 3 - Alpha", + "Environment :: Web Environment", "Framework :: FastAPI", "Intended Audience :: End Users/Desktop", + "Operating System :: OS Independent", "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Topic :: Multimedia :: Graphics", ] @@ -42,6 +50,8 @@ pasteup = "pasteup.cli:main" [project.urls] Source = "https://github.com/ftymoshchuk/pasteup" +Issues = "https://github.com/ftymoshchuk/pasteup/issues" +Changelog = "https://github.com/ftymoshchuk/pasteup/blob/main/CHANGELOG.md" [tool.hatch.version] path = "src/pasteup/__init__.py" diff --git a/src/pasteup/cli.py b/src/pasteup/cli.py index 0a01d99..08bebbc 100644 --- a/src/pasteup/cli.py +++ b/src/pasteup/cli.py @@ -1,26 +1,54 @@ -"""The `pasteup` command: serve the app locally.""" +"""The `pasteup` command: start the app and open it in the browser.""" from __future__ import annotations import argparse +import json +import os +import shutil +import socket import sys +import threading +import time +import urllib.request +import webbrowser from pasteup import __version__ LOCAL_HOSTS = ("127.0.0.1", "localhost", "::1") +WILDCARD_HOSTS = {"0.0.0.0": "127.0.0.1", "::": "::1"} +DEFAULT_PORT = 8000 +# Ports tried after the default when another program holds it. +FALLBACK_PORTS = 10 +BROWSER_WAIT_SECONDS = 20 + +# Asking the local server must not go through a proxy set in the environment. +_local_opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) def main(argv: list[str] | None = None) -> None: parser = argparse.ArgumentParser( prog="pasteup", - description="Turn a folder of clip art into listing images. Serves the app in your browser.", + description="Turn a folder of clip art into listing images. Starts the app and opens it in your browser.", ) parser.add_argument("--host", default="127.0.0.1", help="address to listen on (default: 127.0.0.1)") - parser.add_argument("--port", type=int, default=8000, help="port to listen on (default: 8000)") + parser.add_argument( + "--port", type=_port_number, help=f"port to listen on (default: {DEFAULT_PORT}, or the next free one)" + ) + parser.add_argument("--no-browser", action="store_true", help="don't open the app in a browser") + parser.add_argument( + "--shortcut", action="store_true", help="put a Pasteup launcher on your desktop, then exit" + ) parser.add_argument("--reload", action="store_true", help="restart on code changes, for development") parser.add_argument("--version", action="version", version=f"pasteup {__version__}") args = parser.parse_args(argv) + if args.shortcut: + from pasteup.shortcut import create_shortcut + + print(create_shortcut()) + return + if args.host not in LOCAL_HOSTS: print( f"Warning: listening on {args.host} lets other machines reach an app that reads and " @@ -28,7 +56,116 @@ def main(argv: list[str] | None = None) -> None: file=sys.stderr, ) + visit_host = WILDCARD_HOSTS.get(args.host, args.host) + open_browser = not args.no_browser and _can_open_browser(visit_host) + port, state = _choose_port(visit_host, args.port) + url = _base_url(visit_host, port) + + if state == "pasteup": + print(f"Pasteup is already running at {url}") + if open_browser: + webbrowser.open(url) + return + + if port != (args.port or DEFAULT_PORT): + print(f"Port {DEFAULT_PORT} is taken by another program, so Pasteup is using {port}.") + print(f"Pasteup is running at {url}") + if open_browser: + print("Opening it in your browser...") + _open_when_ready(url) + else: + print("Open that address in your browser.") + print("Keep this window open while you use Pasteup; press Ctrl+C to stop it.") + if shutil.which("ffmpeg") is None: + print( + "Note: preview videos need ffmpeg (https://ffmpeg.org), which isn't installed. " + "Everything else works." + ) + sys.stdout.flush() + # Imported here so `pasteup --help` and `--version` stay instant. import uvicorn - uvicorn.run("pasteup.main:app", host=args.host, port=args.port, reload=args.reload) + uvicorn.run( + "pasteup.main:app", + host=args.host, + port=port, + reload=args.reload, + # Errors only, unless developing: request logs mean nothing to a user. + log_level="info" if args.reload else "warning", + ) + print("Pasteup has stopped.") + + +def _port_number(value: str) -> int: + port = int(value) + if not 1 <= port <= 65535: + raise argparse.ArgumentTypeError("must be between 1 and 65535") + return port + + +def _choose_port(host: str, requested_port: int | None) -> tuple[int, str]: + """Return the port to use, and "pasteup" when Pasteup already runs there.""" + if requested_port is not None: + state = _probe(host, requested_port) + if state == "busy": + sys.exit(f"Port {requested_port} is in use by another program. Choose a different one with --port.") + return requested_port, state + + for port in range(DEFAULT_PORT, DEFAULT_PORT + FALLBACK_PORTS + 1): + state = _probe(host, port) + if state != "busy": + return port, state + sys.exit( + f"Ports {DEFAULT_PORT} to {DEFAULT_PORT + FALLBACK_PORTS} are all in use by other programs. " + "Choose a free one with --port." + ) + + +def _probe(host: str, port: int) -> str: + """Say whether a port is "free", has Pasteup on it ("pasteup") or another program ("busy").""" + try: + with socket.create_connection((host, port), timeout=0.5): + pass + except OSError: + return "free" + return "pasteup" if _answers_as_pasteup(_base_url(host, port)) else "busy" + + +def _answers_as_pasteup(url: str) -> bool: + try: + with _local_opener.open(f"{url}api/jobs/health", timeout=2) as response: + return json.load(response).get("app") == "pasteup" + except (OSError, ValueError, AttributeError): + return False + + +def _open_when_ready(url: str) -> None: + """Open the browser once the server answers, without holding up its start.""" + threading.Thread(target=_wait_then_open, args=(url,), daemon=True).start() + + +def _wait_then_open(url: str, timeout: float = BROWSER_WAIT_SECONDS) -> None: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if _answers_as_pasteup(url): + webbrowser.open(url) + return + time.sleep(0.25) + + +def _can_open_browser(host: str) -> bool: + # A browser on this machine can reach only a server listening on it. + if host not in LOCAL_HOSTS: + return False + if os.environ.get("BROWSER"): + return True + # Without a display, Python falls back to text browsers such as lynx, which + # would take over this terminal. + if sys.platform.startswith(("linux", "freebsd", "openbsd", "netbsd")): + return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")) + return True + + +def _base_url(host: str, port: int) -> str: + return f"http://[{host}]:{port}/" if ":" in host else f"http://{host}:{port}/" diff --git a/src/pasteup/routes/jobs.py b/src/pasteup/routes/jobs.py index 3b96479..3514650 100644 --- a/src/pasteup/routes/jobs.py +++ b/src/pasteup/routes/jobs.py @@ -7,6 +7,7 @@ from fastapi import APIRouter, HTTPException from fastapi.responses import JSONResponse +from pasteup import __version__ from pasteup.models.schemas import ( BatchBundleResult, BatchCoverCollageGenerationRequest, @@ -96,7 +97,8 @@ def geometry(self, *, page_width: float, page_height: float) -> PageGeometry: @router.get("/health") def health_check() -> dict[str, str]: - return {"status": "ok"} + # "app" lets `pasteup` tell a running Pasteup from another program on its port. + return {"status": "ok", "app": "pasteup", "version": __version__} @router.post("/scan-folder", response_model=ScanResponse) diff --git a/src/pasteup/shortcut.py b/src/pasteup/shortcut.py new file mode 100644 index 0000000..491d6fb --- /dev/null +++ b/src/pasteup/shortcut.py @@ -0,0 +1,97 @@ +"""`pasteup --shortcut`: a launcher that starts Pasteup with a double-click. + +The launcher runs this installation's Python by its full path, so it works +without a terminal or a PATH set up for `pasteup`. Run the command again after +moving or reinstalling Pasteup somewhere else. +""" + +from __future__ import annotations + +import os +import shlex +import sys +from importlib.resources import files +from pathlib import Path + +NOTE = "Starts Pasteup. Made by `pasteup --shortcut`; run that again if Pasteup moves." + + +def create_shortcut(platform: str | None = None) -> str: + """Write a launcher for this platform and return a sentence saying where it is.""" + platform = platform or sys.platform + + if platform == "darwin": + # Double-clicking a .command file runs it in Terminal. + path = _existing_dir(Path.home() / "Desktop") / "Pasteup.command" + _write(path, f"#!/bin/sh\n# {NOTE}\nexec {shlex.quote(sys.executable)} -m pasteup\n", executable=True) + return f"Made {path}. Double-click it to start Pasteup." + + if platform == "win32": + path = _windows_desktop() / "Pasteup.bat" + python = sys.executable.replace("%", "%%") + # chcp 65001 makes cmd read the rest as UTF-8, for a path with accents in + # it; the pause keeps an error on screen instead of closing the window. + script = ( + f'@echo off\r\nchcp 65001 >nul\r\nrem {NOTE}\r\n"{python}" -m pasteup\r\nif errorlevel 1 pause\r\n' + ) + _write(path, script) + return f"Made {path}. Double-click it to start Pasteup." + + data_home = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share") + path = data_home / "applications" / "pasteup.desktop" + _write(path, _desktop_entry(), executable=True) + return f"Added Pasteup to your applications menu ({path})." + + +def _desktop_entry() -> str: + lines = [ + "[Desktop Entry]", + "Type=Application", + "Name=Pasteup", + "Comment=Turn a folder of clip art into listing images", + f"Exec={_desktop_exec_argument(sys.executable)} -m pasteup", + "Terminal=true", + "Categories=Graphics;", + ] + icon = Path(str(files("pasteup") / "static" / "favicon.svg")) + if icon.is_file(): + lines.append(f"Icon={icon}") + return "\n".join(lines) + "\n" + + +def _desktop_exec_argument(value: str) -> str: + """Quote one Exec argument as the desktop entry specification requires.""" + for reserved in ("\\", '"', "`", "$"): + value = value.replace(reserved, "\\" + reserved) + # "%" starts a field code, and the value as a whole escapes backslashes again. + return f'"{value}"'.replace("%", "%%").replace("\\", "\\\\") + + +def _windows_desktop() -> Path: + # The Desktop folder can be moved, most often into OneDrive; the registry + # says where it is now. + try: + import winreg + + with winreg.OpenKey( + winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" + ) as key: + desktop = Path(os.path.expandvars(winreg.QueryValueEx(key, "Desktop")[0])) + if desktop.is_dir(): + return desktop + except (ImportError, OSError): + pass + return _existing_dir(Path.home() / "Desktop") + + +def _existing_dir(preferred: Path) -> Path: + return preferred if preferred.is_dir() else Path.home() + + +def _write(path: Path, content: str, *, executable: bool = False) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + # newline="" keeps the line endings written above, CRLF included. + with path.open("w", encoding="utf-8", newline="") as handle: + handle.write(content) + if executable: + path.chmod(0o755) diff --git a/tests/test_cli.py b/tests/test_cli.py index 4428432..3d3fe35 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,9 +1,34 @@ +import shlex +import socket import subprocess import sys +import threading +import time import pytest +import uvicorn -from pasteup import __version__, cli +from pasteup import __version__, cli, shortcut +from pasteup.main import app + + +@pytest.fixture +def launch(monkeypatch): + """Run `pasteup` with the server, the browser and the port probe replaced.""" + served, opened, scheduled = [], [], [] + monkeypatch.setattr("uvicorn.run", lambda target, **kwargs: served.append((target, kwargs))) + monkeypatch.setattr("webbrowser.open", opened.append) + monkeypatch.setattr(cli, "_open_when_ready", scheduled.append) + monkeypatch.setattr(cli, "_can_open_browser", lambda host: True) + ports = {} + monkeypatch.setattr(cli, "_probe", lambda host, port: ports.get(port, "free")) + + def run(*argv): + cli.main(list(argv)) + return served, opened, scheduled + + run.ports = ports + return run def test_version_flag_prints_the_package_version(capsys) -> None: @@ -14,23 +39,75 @@ def test_version_flag_prints_the_package_version(capsys) -> None: assert capsys.readouterr().out.strip() == f"pasteup {__version__}" -def test_serves_the_app_on_this_machine_by_default(monkeypatch) -> None: - calls = [] - monkeypatch.setattr("uvicorn.run", lambda app, **kwargs: calls.append((app, kwargs))) +def test_serves_the_app_on_this_machine_and_opens_it(launch, capsys) -> None: + served, opened, scheduled = launch() + + assert served == [ + ("pasteup.main:app", {"host": "127.0.0.1", "port": 8000, "reload": False, "log_level": "warning"}) + ] + assert scheduled == ["http://127.0.0.1:8000/"] + output = capsys.readouterr().out + assert "Pasteup is running at http://127.0.0.1:8000/" in output + assert "press Ctrl+C to stop it" in output + + +def test_no_browser_leaves_the_browser_alone(launch, capsys) -> None: + served, opened, scheduled = launch("--no-browser") - cli.main([]) + assert served and not scheduled and not opened + assert "Open that address in your browser." in capsys.readouterr().out - assert calls == [("pasteup.main:app", {"host": "127.0.0.1", "port": 8000, "reload": False})] +def test_a_running_pasteup_is_opened_instead_of_started_twice(launch, capsys) -> None: + launch.ports[8000] = "pasteup" -def test_warns_when_listening_beyond_this_machine(monkeypatch, capsys) -> None: - monkeypatch.setattr("uvicorn.run", lambda app, **kwargs: None) + served, opened, _ = launch() - cli.main(["--host", "0.0.0.0", "--port", "9000"]) + assert served == [] + assert opened == ["http://127.0.0.1:8000/"] + assert "already running at http://127.0.0.1:8000/" in capsys.readouterr().out + + +def test_moves_to_the_next_free_port_when_another_program_has_the_default(launch, capsys) -> None: + launch.ports.update({8000: "busy", 8001: "busy"}) + + served, _, scheduled = launch() + + assert served[0][1]["port"] == 8002 + assert scheduled == ["http://127.0.0.1:8002/"] + assert "Port 8000 is taken by another program, so Pasteup is using 8002." in capsys.readouterr().out + + +def test_a_port_chosen_on_purpose_is_not_swapped(launch) -> None: + launch.ports[9000] = "busy" + + with pytest.raises(SystemExit) as exit_info: + launch("--port", "9000") + + assert "Port 9000 is in use by another program" in str(exit_info.value.code) + + +@pytest.mark.parametrize("port", ["0", "70000", "eighty"]) +def test_a_port_outside_the_valid_range_is_refused(port, capsys) -> None: + with pytest.raises(SystemExit) as exit_info: + cli.main(["--port", port]) + + assert exit_info.value.code == 2 + assert "--port" in capsys.readouterr().err + + +def test_warns_when_listening_beyond_this_machine(launch, capsys) -> None: + launch("--host", "0.0.0.0", "--port", "9000") assert "See SECURITY.md" in capsys.readouterr().err +def test_a_wildcard_address_is_opened_through_this_machine(launch) -> None: + _, _, scheduled = launch("--host", "0.0.0.0") + + assert scheduled == ["http://127.0.0.1:8000/"] + + def test_python_dash_m_runs_the_same_command() -> None: result = subprocess.run( [sys.executable, "-m", "pasteup", "--version"], @@ -40,3 +117,96 @@ def test_python_dash_m_runs_the_same_command() -> None: ) assert result.stdout.strip() == f"pasteup {__version__}" + + +def test_no_browser_without_a_display_on_linux(monkeypatch) -> None: + """Python would fall back to a text browser that takes over the terminal.""" + monkeypatch.setattr(sys, "platform", "linux") + for name in ("BROWSER", "DISPLAY", "WAYLAND_DISPLAY"): + monkeypatch.delenv(name, raising=False) + + assert not cli._can_open_browser("127.0.0.1") + + monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0") + assert cli._can_open_browser("127.0.0.1") + assert not cli._can_open_browser("192.168.1.20") + + +def _free_port() -> int: + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +def test_probe_tells_pasteup_from_other_programs() -> None: + port = _free_port() + assert cli._probe("127.0.0.1", port) == "free" + + server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error")) + thread = threading.Thread(target=server.run, daemon=True) + thread.start() + try: + deadline = time.monotonic() + 10 + while not server.started and time.monotonic() < deadline: + time.sleep(0.02) + assert cli._probe("127.0.0.1", port) == "pasteup" + finally: + server.should_exit = True + thread.join(timeout=10) + + with socket.socket() as other_program: + # The port can still hold the closed server's connections in TIME_WAIT. + other_program.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + other_program.bind(("127.0.0.1", port)) + other_program.listen() + assert cli._probe("127.0.0.1", port) == "busy" + + +def test_shortcut_flag_writes_the_launcher_and_exits(launch, monkeypatch, capsys) -> None: + monkeypatch.setattr(shortcut, "create_shortcut", lambda: "Made a launcher.") + + served, _, _ = launch("--shortcut") + + assert served == [] + assert capsys.readouterr().out.strip() == "Made a launcher." + + +def test_macos_shortcut_runs_this_python(monkeypatch, tmp_path) -> None: + monkeypatch.setenv("HOME", str(tmp_path)) + (tmp_path / "Desktop").mkdir() + + message = shortcut.create_shortcut("darwin") + + launcher = tmp_path / "Desktop" / "Pasteup.command" + assert str(launcher) in message + assert launcher.stat().st_mode & 0o111 + script = launcher.read_text() + assert script.startswith("#!/bin/sh\n") + assert shlex.split(script.splitlines()[-1]) == ["exec", sys.executable, "-m", "pasteup"] + subprocess.run(["sh", "-n", str(launcher)], check=True) + + +def test_windows_shortcut_runs_this_python(monkeypatch, tmp_path) -> None: + monkeypatch.setattr(shortcut, "_windows_desktop", lambda: tmp_path) + + shortcut.create_shortcut("win32") + + script = (tmp_path / "Pasteup.bat").read_bytes().decode("utf-8") + assert script.startswith("@echo off\r\nchcp 65001 >nul\r\n") + assert f'\r\n"{sys.executable}" -m pasteup\r\n' in script + assert "\n" not in script.replace("\r\n", "") + + +def test_linux_shortcut_is_an_applications_menu_entry(monkeypatch, tmp_path) -> None: + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path)) + + message = shortcut.create_shortcut("linux") + + entry = (tmp_path / "applications" / "pasteup.desktop").read_text() + assert "applications menu" in message + assert f'Exec="{sys.executable}" -m pasteup' in entry + assert "Terminal=true" in entry + + +def test_desktop_entry_quoting_follows_the_specification() -> None: + assert shortcut._desktop_exec_argument('/opt/my "py"/$HOME/100%') == '"/opt/my \\\\"py\\\\"/\\\\$HOME/100%%"'