Miva
Claude Sonnet 4.6
feat: version_alpha_2 β language switcher, YouTube fix, form improvements
0f2ae9e Download deployer.py from edward70/sitegen: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/edward70/sitegen/resolve/main/deployer.py
- Command line
-
hf download hf://spaces/edward70/sitegen/deployer.py
-
curl -L -o deployer.py https://huggingface.co/spaces/edward70/sitegen/resolve/main/deployer.py
12.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| Site Deployer | |
| 1. Push source files to GitHub (creates private repo per client) | |
| 2. Deploy directly to Cloudflare Pages (creates project if new) | |
| Returns: https://{slug}.pages.dev | |
| Required env vars: | |
| GITHUB_TOKEN - Personal access token (repo scope) | |
| GITHUB_USERNAME - GitHub username or org name | |
| CF_API_TOKEN - Cloudflare API token (Pages:Edit permission) | |
| CF_ACCOUNT_ID - Cloudflare account ID (Dashboard β right sidebar) | |
| """ | |
| import base64 | |
| import hashlib | |
| import json | |
| import os | |
| import shutil | |
| import subprocess | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| import requests | |
| # βββ GitHub βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| class GitHubDeployer: | |
| BASE = "https://api.github.com" | |
| def __init__(self, token: str, username: str): | |
| self._headers = { | |
| "Authorization": f"Bearer {token}", | |
| "Accept": "application/vnd.github+json", | |
| "X-GitHub-Api-Version": "2022-11-28", | |
| } | |
| self.username = username | |
| def ensure_repo(self, slug: str, description: str = "") -> str: | |
| """Create repo if it doesn't exist. Returns full name owner/repo.""" | |
| repo_name = f"site-{slug}" | |
| r = requests.get( | |
| f"{self.BASE}/repos/{self.username}/{repo_name}", | |
| headers=self._headers, | |
| ) | |
| if r.status_code == 200: | |
| print(f" GitHub: repo already exists β {r.json()['html_url']}") | |
| return r.json()["full_name"] | |
| r = requests.post( | |
| f"{self.BASE}/user/repos", | |
| headers=self._headers, | |
| json={ | |
| "name": repo_name, | |
| "description": description or f"Website: {slug}", | |
| "private": False, | |
| "auto_init": False, | |
| }, | |
| ) | |
| _raise(r, "GitHub create repo") | |
| url = r.json()["html_url"] | |
| print(f" GitHub: created repo β {url}") | |
| return r.json()["full_name"] | |
| def push_files(self, repo_full_name: str, files: dict[str, "str | bytes"], branch: str = "main"): | |
| """Upsert every file in the repo on the given branch.""" | |
| for path, content in files.items(): | |
| encoded = base64.b64encode(content if isinstance(content, bytes) else content.encode("utf-8")).decode() | |
| url = f"{self.BASE}/repos/{repo_full_name}/contents/{path}" | |
| existing = requests.get(url, headers=self._headers, params={"ref": branch}) | |
| sha = existing.json().get("sha") if existing.status_code == 200 else None | |
| payload: dict = { | |
| "message": f"deploy: update {path}", | |
| "content": encoded, | |
| "branch": branch, | |
| } | |
| if sha: | |
| payload["sha"] = sha | |
| r = requests.put(url, headers=self._headers, json=payload) | |
| _raise(r, f"GitHub push {path}") | |
| print(f" GitHub: pushed {path}") | |
| # βββ Cloudflare Pages Direct Upload βββββββββββββββββββββββββββββββββββββββββββ | |
| class CloudflareDeployer: | |
| BASE = "https://api.cloudflare.com/client/v4" | |
| def __init__(self, token: str, account_id: str): | |
| self._token = token | |
| self._headers = {"Authorization": f"Bearer {token}"} | |
| self.account_id = account_id | |
| def ensure_project(self, slug: str) -> str: | |
| """Create Pages project if it doesn't exist. Returns project name.""" | |
| name = slug | |
| r = requests.get( | |
| f"{self.BASE}/accounts/{self.account_id}/pages/projects/{name}", | |
| headers=self._headers, | |
| ) | |
| if r.status_code == 200: | |
| print(f" Cloudflare: project exists β {name}") | |
| return name | |
| r = requests.post( | |
| f"{self.BASE}/accounts/{self.account_id}/pages/projects", | |
| headers=self._headers, | |
| json={"name": name, "production_branch": "main"}, | |
| ) | |
| _raise(r, "Cloudflare create project") | |
| print(f" Cloudflare: created project β {name}") | |
| return name | |
| def deploy(self, project_name: str, files: dict[str, "str | bytes"]) -> str: | |
| """Deploy files via wrangler pages deploy.""" | |
| wrangler = self._find_wrangler() | |
| with tempfile.TemporaryDirectory() as tmp: | |
| for name, content in files.items(): | |
| p = Path(tmp, name) | |
| if isinstance(content, bytes): | |
| p.write_bytes(content) | |
| else: | |
| p.write_text(content, encoding="utf-8") | |
| return self._wrangler_deploy(wrangler, tmp, project_name) | |
| def deploy_dir(self, dir_path: "Path | str", project_name: str) -> str: | |
| """Deploy a directory directly β wrangler handles all file types including images.""" | |
| wrangler = self._find_wrangler() | |
| return self._wrangler_deploy(wrangler, str(dir_path), project_name) | |
| def _wrangler_deploy(self, wrangler: str, directory: str, project_name: str) -> str: | |
| env = { | |
| **os.environ, | |
| "CLOUDFLARE_API_TOKEN": self._token, | |
| "CLOUDFLARE_ACCOUNT_ID": self.account_id, | |
| } | |
| result = subprocess.run( | |
| [wrangler, "pages", "deploy", directory, | |
| "--project-name", project_name, | |
| "--branch", "main", | |
| "--commit-dirty=true"], | |
| capture_output=True, text=True, env=env, | |
| ) | |
| output = result.stdout + result.stderr | |
| print(f" Cloudflare wrangler: {output.strip().splitlines()[-1] if output.strip() else 'done'}") | |
| if result.returncode != 0: | |
| raise RuntimeError(f"wrangler deploy failed:\n{output[-600:]}") | |
| return f"https://{project_name}.pages.dev" | |
| def _find_wrangler(self) -> str: | |
| for candidate in [ | |
| shutil.which("wrangler"), | |
| os.path.expanduser("~/.npm-global/bin/wrangler"), | |
| "/usr/local/bin/wrangler", | |
| ]: | |
| if candidate and Path(candidate).exists(): | |
| return candidate | |
| raise RuntimeError("wrangler not found β run: npm install -g wrangler --prefix ~/.npm-global") | |
| # βββ Orchestrator βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def deploy( | |
| slug: str, | |
| files: dict[str, str], | |
| business_name: str = "", | |
| github: bool = True, | |
| cloudflare: bool = True, | |
| ) -> dict: | |
| """ | |
| Deploy site files for a client. | |
| Args: | |
| slug: URL-safe client identifier (e.g. "green-thumb-gardens") | |
| files: dict of filename β content (e.g. {"index.html": "..."}) | |
| business_name: human-readable name for repo description | |
| github: push source to GitHub | |
| cloudflare: deploy to Cloudflare Pages | |
| Returns: | |
| {"github_repo": str, "live_url": str} | |
| """ | |
| result: dict = {} | |
| if github: | |
| gh = _github_client() | |
| print("\nββ GitHub ββββββββββββββββββββββββββββββ") | |
| repo = gh.ensure_repo(slug, description=business_name) | |
| gh.push_files(repo, files) | |
| result["github_repo"] = f"https://github.com/{repo}" | |
| if cloudflare: | |
| cf = _cloudflare_client() | |
| print("\nββ Cloudflare Pages ββββββββββββββββββββ") | |
| project = cf.ensure_project(slug) | |
| live_url = cf.deploy(project, files) | |
| result["live_url"] = live_url | |
| print(f" Live URL β {live_url}") | |
| return result | |
| def deploy_from_dir(output_dir: Path | str, slug: str, business_name: str = "", | |
| github: bool = True, cloudflare: bool = True) -> dict: | |
| """Deploy all site files from disk, including images.""" | |
| output_dir = Path(output_dir) | |
| text_exts = {".html", ".css", ".js", ".json"} | |
| binary_exts = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg", ".ico"} | |
| text_files: dict[str, str] = {} | |
| binary_files: dict[str, bytes] = {} | |
| for fp in output_dir.iterdir(): | |
| if fp.suffix in text_exts: | |
| text_files[fp.name] = fp.read_text(encoding="utf-8") | |
| elif fp.suffix in binary_exts: | |
| binary_files[fp.name] = fp.read_bytes() | |
| if not text_files: | |
| raise ValueError(f"No .html/.css/.js files found in {output_dir}") | |
| all_files = {**text_files, **binary_files} | |
| print(f"Deploying {len(all_files)} file(s): {', '.join(sorted(all_files))}") | |
| result: dict = {} | |
| if github: | |
| gh = _github_client() | |
| print("\nββ GitHub ββββββββββββββββββββββββββββββ") | |
| repo = gh.ensure_repo(slug, description=business_name) | |
| gh.push_files(repo, all_files) | |
| result["github_repo"] = f"https://github.com/{repo}" | |
| if cloudflare: | |
| cf = _cloudflare_client() | |
| print("\nββ Cloudflare Pages ββββββββββββββββββββ") | |
| project = cf.ensure_project(slug) | |
| live_url = cf.deploy_dir(output_dir, project) | |
| result["live_url"] = live_url | |
| print(f" Live URL β {live_url}") | |
| return result | |
| # βββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def _github_client() -> GitHubDeployer: | |
| token = os.environ.get("GITHUB_TOKEN") | |
| username = os.environ.get("GITHUB_USERNAME") | |
| if not token: | |
| raise EnvironmentError("GITHUB_TOKEN not set") | |
| if not username: | |
| raise EnvironmentError("GITHUB_USERNAME not set") | |
| return GitHubDeployer(token, username) | |
| def _cloudflare_client() -> CloudflareDeployer: | |
| token = os.environ.get("CF_API_TOKEN") | |
| account_id = os.environ.get("CF_ACCOUNT_ID") | |
| if not token: | |
| raise EnvironmentError("CF_API_TOKEN not set") | |
| if not account_id: | |
| raise EnvironmentError("CF_ACCOUNT_ID not set") | |
| return CloudflareDeployer(token, account_id) | |
| def _raise(r: requests.Response, label: str): | |
| if not r.ok: | |
| raise RuntimeError(f"{label} failed [{r.status_code}]: {r.text[:500]}") | |
| def _cf_ok(data: dict, label: str): | |
| if not data.get("success"): | |
| errors = data.get("errors", []) | |
| raise RuntimeError(f"{label} API error: {errors}") | |
| def _mime(path: str) -> str: | |
| ext = path.rsplit(".", 1)[-1].lower() | |
| return { | |
| "html": "text/html", | |
| "css": "text/css", | |
| "js": "application/javascript", | |
| "json": "application/json", | |
| "png": "image/png", | |
| "jpg": "image/jpeg", | |
| "svg": "image/svg+xml", | |
| "ico": "image/x-icon", | |
| "woff2": "font/woff2", | |
| }.get(ext, "application/octet-stream") | |
| # βββ CLI / demo βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| if __name__ == "__main__": | |
| import sys | |
| if len(sys.argv) >= 3: | |
| output_path, slug = sys.argv[1], sys.argv[2] | |
| name = sys.argv[3] if len(sys.argv) > 3 else slug | |
| result = deploy_from_dir(output_path, slug, name) | |
| else: | |
| # Quick smoke-test with tiny files (won't actually deploy without creds) | |
| test_files = { | |
| "index.html": "<html><body><h1>Test</h1></body></html>", | |
| "style.css": "body { font-family: sans-serif; }", | |
| "script.js": "console.log('hello');", | |
| } | |
| print("Usage: python deployer.py <output_dir> <slug> [business_name]") | |
| print("\nExample deploy (dry-run β set env vars to run for real):") | |
| print(f" Files: {list(test_files)}") | |
| print(" Set: GITHUB_TOKEN, GITHUB_USERNAME, CF_API_TOKEN, CF_ACCOUNT_ID") | |
| sys.exit(0) | |
| print(f"\nResult: {json.dumps(result, indent=2)}") | |