From c5569b60b25f26a55ce637b85507776dec8dd30b Mon Sep 17 00:00:00 2001 From: Clea Aumont Date: Tue, 1 Dec 2026 12:11:38 -0500 Subject: [PATCH] cicd --- .github/scripts/plotly_cloud_ci.py | 222 ++++++++++++++++++++++ .github/workflows/plotly-cloud-deploy.yml | 92 +++++++++ 2 files changed, 314 insertions(+) create mode 100644 .github/scripts/plotly_cloud_ci.py create mode 100644 .github/workflows/plotly-cloud-deploy.yml diff --git a/.github/scripts/plotly_cloud_ci.py b/.github/scripts/plotly_cloud_ci.py new file mode 100644 index 0000000..aca9c8c --- /dev/null +++ b/.github/scripts/plotly_cloud_ci.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +"""CI helper for publishing the apps in this monorepo to Plotly Cloud. + +Subcommands +----------- + changed Print the app folders the PR touches (JSON list). + staging ... Publish each app as "-staging" (create or update). + teardown ... Delete each "-staging" app, if it exists. + production ... Publish each app to its production app (update or create). + +Every app is published into the team named by PLOTLY_TEAM. Auth comes from +PLOTLY_API_KEY, which both this script and the `plotly` CLI read. + +An "app" is a top-level folder with an app.py in it. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import tempfile +import tomllib +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parents[2] +API = "https://cloud.plotly.com/api" +STAGING_SUFFIX = "-staging" +# Folders that look like apps but aren't deployable on their own. +NOT_APPS = {"shared_components"} +# Left out of the staging copy so the production app_id in plotly-cloud.toml +# never leaks into, or gets overwritten by, a staging publish. +STAGING_IGNORE = shutil.ignore_patterns( + "plotly-cloud.toml", "__pycache__", ".DS_Store", "*.pyc", ".venv", "venv" +) + + +def log(msg: str) -> None: + print(msg, file=sys.stderr, flush=True) + + +def summary(md: str) -> None: + """Append to the job summary and to the PR-comment file, when set.""" + for var in ("GITHUB_STEP_SUMMARY", "PR_COMMENT_FILE"): + path = os.environ.get(var) + if path: + with open(path, "a") as f: + f.write(md + "\n") + + +# --------------------------------------------------------------------------- # +# Plotly Cloud API +# --------------------------------------------------------------------------- # +def client(): + import httpx # installed with plotly-cloud; not needed for `changed` + + key = os.environ.get("PLOTLY_API_KEY") + if not key: + sys.exit("PLOTLY_API_KEY is not set") + return httpx.Client( + base_url=API, + headers={"Authorization": f"Bearer {key}", "user-agent": "PlotlyCloudCLI"}, + timeout=60, + ) + + +def team_id(c) -> str: + wanted = os.environ.get("PLOTLY_TEAM", "").strip() + if not wanted: + sys.exit("PLOTLY_TEAM is not set") + r = c.get("/teams") + r.raise_for_status() + teams = r.json() + for t in teams: + if wanted.lower() in (t.get("name", "").lower(), t.get("id", "").lower()): + return t["id"] + names = ", ".join(t.get("name", "?") for t in teams) or "(none)" + sys.exit(f"Team '{wanted}' not found. This API key can see: {names}") + + +def team_apps(c, tid: str) -> list[dict]: + r = c.get("/apps", params={"teamId": tid}) + r.raise_for_status() + return r.json() + + +def find_by_name(apps: list[dict], name: str) -> dict | None: + matches = [a for a in apps if a.get("name") == name] + if len(matches) > 1: + log(f"warning: {len(matches)} apps named '{name}'; using the most recently published") + matches.sort(key=lambda a: a.get("last_published") or a.get("created_at") or "", reverse=True) + return matches[0] if matches else None + + +def app_link(app: dict | None) -> str: + if app and app.get("app_url"): + return f"https://{app['app_url']}.plotly.app" + return "(url unavailable)" + + +def publish(project: Path, tid: str, *, app_id: str | None = None, name: str | None = None) -> None: + cmd = [ + "plotly", "app", "publish", + "--project-path", str(project), + "--team-id", tid, + "--poll-timeout", "900", + ] + cmd += ["--app-id", app_id] if app_id else ["--name", name] + log("$ " + " ".join(cmd)) + subprocess.run(cmd, check=True) + + +# --------------------------------------------------------------------------- # +# Commands +# --------------------------------------------------------------------------- # +def cmd_changed(pr: str) -> None: + out = subprocess.run( + ["gh", "pr", "diff", pr, "--name-only"], + check=True, capture_output=True, text=True, cwd=REPO_ROOT, + ).stdout + apps = sorted( + { + top + for line in out.splitlines() + if "/" in line + and (top := line.split("/", 1)[0]) not in NOT_APPS + and (REPO_ROOT / top / "app.py").is_file() + } + ) + print(json.dumps(apps)) + + +def cmd_staging(apps: list[str]) -> None: + with client() as c: + tid = team_id(c) + summary("### Staging apps\n") + for app in apps: + name = f"{app}{STAGING_SUFFIX}" + existing = find_by_name(team_apps(c, tid), name) + with tempfile.TemporaryDirectory() as tmp: + project = Path(tmp) / app + shutil.copytree(REPO_ROOT / app, project, ignore=STAGING_IGNORE) + if existing: + log(f"Updating {name} ({existing['id']})") + publish(project, tid, app_id=existing["id"]) + else: + log(f"Creating {name}") + publish(project, tid, name=name) + deployed = find_by_name(team_apps(c, tid), name) + summary(f"- **{app}** → {app_link(deployed)}") + + +def cmd_teardown(apps: list[str]) -> None: + with client() as c: + tid = team_id(c) + all_apps = team_apps(c, tid) + summary("### Staging teardown\n") + for app in apps: + name = f"{app}{STAGING_SUFFIX}" + victims = [a for a in all_apps if a.get("name") == name] + if not victims: + summary(f"- {name}: nothing to delete") + continue + for a in victims: + r = c.delete(f"/app/{a['id']}") + if r.status_code in (200, 202, 204, 404): + summary(f"- {name}: deleted ({a['id']})") + else: + sys.exit(f"Deleting {name} ({a['id']}) failed: {r.status_code} {r.text}") + + +def cmd_production(apps: list[str]) -> None: + with client() as c: + tid = team_id(c) + summary("### Production apps\n") + for app in apps: + project = REPO_ROOT / app + toml_path = project / "plotly-cloud.toml" + cfg = tomllib.loads(toml_path.read_text()) if toml_path.is_file() else {} + apps_in_team = team_apps(c, tid) + by_id = {a.get("id"): a for a in apps_in_team} + + # 1. The app recorded in plotly-cloud.toml, if it lives in this team. + target = by_id.get(cfg.get("app_id")) + # 2. Otherwise an app in this team with the same name. + name = cfg.get("name") or app + target = target or find_by_name(apps_in_team, name) + + if target: + log(f"Updating {target.get('name')} ({target['id']})") + publish(project, tid, app_id=target["id"]) + else: + if cfg.get("app_id"): + log( + f"warning: app_id {cfg['app_id']} in {app}/plotly-cloud.toml is not in " + f"team '{os.environ['PLOTLY_TEAM']}'; creating a new app there" + ) + log(f"Creating {name}") + publish(project, tid, name=name) + + deployed = find_by_name(team_apps(c, tid), name) or target + summary(f"- **{app}** → {app_link(deployed)}") + + +def main() -> None: + if len(sys.argv) < 2: + sys.exit(__doc__) + cmd, args = sys.argv[1], sys.argv[2:] + if cmd == "changed": + cmd_changed(args[0]) + return + for a in args if cmd != "teardown" else []: + if a in NOT_APPS or not (REPO_ROOT / a / "app.py").is_file(): + sys.exit(f"'{a}' is not an app folder") + {"staging": cmd_staging, "teardown": cmd_teardown, "production": cmd_production}[cmd](args) + + +if __name__ == "__main__": + main() diff --git a/.github/workflows/plotly-cloud-deploy.yml b/.github/workflows/plotly-cloud-deploy.yml new file mode 100644 index 0000000..6427fa0 --- /dev/null +++ b/.github/workflows/plotly-cloud-deploy.yml @@ -0,0 +1,92 @@ +name: Plotly Cloud deploy + +# PR opened/updated -> publish each changed app as "-staging" +# PR merged -> delete "-staging", then update/create the production app +# PR closed unmerged -> delete "-staging" +on: + pull_request: + types: [opened, synchronize, reopened, closed] + branches: [main] + +# One run per PR at a time; a new push cancels an in-flight staging deploy, +# but never cancel a merge deploy halfway through. +concurrency: + group: plotly-cloud-${{ github.event.pull_request.number }} + cancel-in-progress: ${{ github.event.action != 'closed' }} + +permissions: + contents: read + pull-requests: write + +env: + PLOTLY_API_KEY: ${{ secrets.PLOTLY_API_KEY }} + PLOTLY_TEAM: ${{ vars.PLOTLY_TEAM || 'Marketing' }} + PLOTLY_CLOUD_VERSION: "0.6.0" + GH_TOKEN: ${{ github.token }} + +jobs: + changes: + runs-on: ubuntu-latest + outputs: + apps: ${{ steps.detect.outputs.apps }} + any: ${{ steps.detect.outputs.any }} + steps: + - uses: actions/checkout@v4 + - id: detect + run: | + apps=$(python3 .github/scripts/plotly_cloud_ci.py changed "${{ github.event.pull_request.number }}") + echo "Changed apps: $apps" + echo "apps=$apps" >> "$GITHUB_OUTPUT" + [ "$apps" = "[]" ] && echo "any=false" >> "$GITHUB_OUTPUT" || echo "any=true" >> "$GITHUB_OUTPUT" + + staging: + needs: changes + if: github.event.action != 'closed' && needs.changes.outputs.any == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: pip install "plotly-cloud==${PLOTLY_CLOUD_VERSION}" + - name: Publish staging apps + env: + PR_COMMENT_FILE: ${{ runner.temp }}/comment.md + run: | + echo "" > "$PR_COMMENT_FILE" + python .github/scripts/plotly_cloud_ci.py staging $(echo '${{ needs.changes.outputs.apps }}' | jq -r '.[]') + - name: Comment staging links on the PR + if: always() + run: | + gh pr comment "${{ github.event.pull_request.number }}" \ + --body-file "${{ runner.temp }}/comment.md" --edit-last --create-if-none + + teardown: + needs: changes + if: github.event.action == 'closed' && needs.changes.outputs.any == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: pip install "plotly-cloud==${PLOTLY_CLOUD_VERSION}" + - name: Delete staging apps + run: python .github/scripts/plotly_cloud_ci.py teardown $(echo '${{ needs.changes.outputs.apps }}' | jq -r '.[]') + + production: + needs: [changes, teardown] + # Run even if teardown failed: a leftover staging app shouldn't block the release. + if: ${{ !cancelled() && github.event.action == 'closed' && github.event.pull_request.merged == true && needs.changes.outputs.any == 'true' }} + runs-on: ubuntu-latest + environment: production + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.merge_commit_sha }} + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: pip install "plotly-cloud==${PLOTLY_CLOUD_VERSION}" + - name: Publish production apps + run: python .github/scripts/plotly_cloud_ci.py production $(echo '${{ needs.changes.outputs.apps }}' | jq -r '.[]')