CommunityCoding & Developmentgithub.com

github-pages-deploy

Deploy static sites to GitHub Pages via Contents API when git push is unavailable. CDN cache busting, multi-language sites, i18n.

What is github-pages-deploy?

github-pages-deploy is a Claude Code agent skill that deploy static sites to GitHub Pages via Contents API when git push is unavailable. CDN cache busting, multi-language sites, i18n.

Works with~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Slime00V/hermes-skills/tree/HEAD/_archive/github-pages-deploy

Installed? Explore more Coding & Development skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

GitHub Pages Deployment

Deploy static sites to GitHub Pages from constrained environments where git push is unavailable (e.g., MSYS on Windows with TLS renegotiation issues).

When to Use This

  • git push fails with TLS/SSL errors like schannel: remote party requests renegotiation
  • Only api.github.com is reachable but github.com is not
  • You can't authenticate via SSH or install gh CLI
  • You need to deploy from a sandboxed Python/API environment

Strategy: Contents API (PUT)

Use the GitHub Contents API (repos/{owner}/{repo}/contents/{path}) to upload files directly. This bypasses git entirely and works via api.github.com which is more reliably accessible.

Key Files

This skill ships with a reusable deploy script. See scripts/deploy_contents_api.py — a self-contained Python script that uploads all site files and enables GitHub Pages.

Deployment Steps

1. Token Setup

Get a classic Personal Access Token with repo scope: https://github.com/settings/tokens/new?scopes=repo&description=site-deploy

CRITICAL: Never paste the token into the chat — GitHub's secret scanning will revoke it. Instead:

  • Ask the user to write it to a local file (deploy_token.txt)
  • Or use a script that reads from a temp file
  • Or prompt the user interactively in-terminal (read -s)

2. Upload Files

import urllib.request, json, base64, os
from urllib.parse import quote

tok = open("deploy_token.txt").read().strip()
base = f"https://api.github.com/repos/{user}/{repo}/contents"

def upload(local_path, api_path):
    with open(local_path, "rb") as f:
        b64 = base64.b64encode(f.read()).decode()
    url = f"{base}/{quote(api_path)}"
    
    # Try creating the file
    payload = json.dumps({"message": f"Add {api_path}", "content": b64, "branch": "main"}).encode()
    req = urllib.request.Request(url, data=payload, method="PUT")
    req.add_header("Authorization", f"token {tok}")
    req.add_header("Content-Type", "application/json")
    
    try:
        urllib.request.urlopen(req)
        return True
    except urllib.error.HTTPError as e:
        # File exists — get SHA and update
        if e.code in (422, 409):
            get_req = urllib.request.Request(url)
            get_req.add_header("Authorization", f"token {tok}")
            sha = json.loads(urllib.request.urlopen(get_req).read()).get("sha", "")
            payload2 = json.dumps({"message": f"Update {api_path}", "content": b64, "sha": sha, "branch": "main"}).encode()
            req2 = urllib.request.Request(url, data=payload2, method="PUT")
            req2.add_header("Authorization", f"token {tok}")
            req2.add_header("Content-Type", "application/json")
            urllib.request.urlopen(req2)
            return True
        return False

3. Enable GitHub Pages

pages_payload = json.dumps({"source": {"branch": "main", "path": "/"}}).encode()
req = urllib.request.Request(
    f"https://api.github.com/repos/{user}/{repo}/pages",
    data=pages_payload, method="POST"
)
req.add_header("Authorization", f"token {tok}")
req.add_header("Content-Type", "application/json")
try:
    urllib.request.urlopen(req)
except urllib.error.HTTPError:
    pass  # May 409 if already enabled

CDN Cache Busting

GitHub Pages uses Fastly CDN which caches aggressively. When new files don't show:

  1. Version query params: Add ?v=TIMESTAMP to script/link hrefs in HTML to force browser cache refresh
  2. Re-upload files: Upload files via Contents API with the same content creates a real new commit with a real tree — Pages auto-detects and rebuilds. This is safer than empty commits.
  3. Wait 1-3 min: CDN typically refreshes within 2 minutes after a build completes

⚠️ Avoid empty commits for cache busting: Creating commits via POST /git/commits + PATCH /git/refs that reference the same tree SHA as the current HEAD can produce phantom commits — the API returns a SHA but the object doesn't persist. Pages tries to build from a non-existent commit, gets stuck in errored state permanently. Fix: Re-upload an existing file via Contents API instead (this always creates a real commit with a real tree), or change an actual file.

Limitations & Known Issues

.github/workflows/ Files Cannot Be Created via Contents API

The Contents API intentionally rejects PUT requests to paths under .github/workflows/. Use one of:

  • GitHub web UI (Add file → Create new file → paste path .github/workflows/file.yml)
  • Git Trees API workaround (see nested tree approach below)
  • Traditional git push

Git Trees API: Creating .github/workflows/ Files

The Contents API can't create files under .github/workflows/, but the Git Data API can via nested trees:

import urllib.request, json, base64
gb = f"https://api.github.com/repos/{user}/{repo}"

# 1. Create blob for the workflow file
b64 = base64.b64encode(yaml_content).decode()
r = urllib.request.Request(f"{gb}/git/blobs",
    data=json.dumps({"content": b64, "encoding": "base64"}).encode(), method="POST")
r.add_header("Authorization", f"token {tok}")
r.add_header("Content-Type", "application/json")
wf_sha = json.loads(urllib.request.urlopen(r).read())["sha"]

# 2. Create workflows/ tree containing the file
t1 = json.dumps({"tree": [{"path": "update-news.yml", "mode": "100644", "type": "blob", "sha": wf_sha}]}).encode()
r = urllib.request.Request(f"{gb}/git/trees", data=t1, method="POST")
r.add_header("Authorization", f"token {tok}")
r.add_header("Content-Type", "application/json")
wf_tree_sha = json.loads(urllib.request.urlopen(r).read())["sha"]

# 3. Create .github tree containing workflows/ subtree
t2 = json.dumps({"tree": [{"path": "workflows", "mode": "040000", "type": "tree", "sha": wf_tree_sha}]}).encode()
r = urllib.request.Request(f"{gb}/git/trees", data=t2, method="POST")
gh_tree_sha = json.loads(urllib.request.urlopen(r).read())["sha"]

# 4. Get current root tree, add .github entry
r = urllib.request.Request(f"{gb}/git/refs/heads/main")
head = json.loads(urllib.request.urlopen(r).read())["object"]["sha"]
r = urllib.request.Request(f"{gb}/git/commits/{head}")
cur_tree_sha = json.loads(urllib.request.urlopen(r).read())["tree"]["sha"]
r = urllib.request.Request(f"{gb}/git/trees/{cur_tree_sha}")
entries = json.loads(urllib.request.urlopen(r).read()).get("tree", [])
entries = [e for e in entries if e["path"] != ".github"]
entries.append({"path": ".github", "mode": "040000", "type": "tree", "sha": gh_tree_sha})

# 5. Create new root tree with base_tree
t3 = json.dumps({"base_tree": cur_tree_sha, "tree": entries}).encode()
r = urllib.request.Request(f"{gb}/git/trees", data=t3, method="POST")
root_sha = json.loads(urllib.request.urlopen(r).read())["sha"]

# 6. Create commit
c = json.dumps({"message": "Add workflow", "tree": root_sha, "parents": [head]}).encode()
r = urllib.request.Request(f"{gb}/git/commits", data=c, method="POST")
c_sha = json.loads(urllib.request.urlopen(r).read())["sha"]

# 7. Update branch ref
r = urllib.request.Request(f"{gb}/git/refs/heads/main",
    data=json.dumps({"sha": c_sha, "force": True}).encode(), method="PATCH")
urllib.request.urlopen(r)

Note: Some token types (fine-grained PATs) may fail at step 7 with "Object does not exist" even though the commit was created. If this happens, use the web UI instead.

Git Data API Commit Persistence

Commit objects created via /git/commits may appear to succeed (return SHA) but fail to persist, showing "Object does not exist" when you try to update the ref. This is a known edge case that happens most often when the commit references a tree SHA already present in the repository (empty commits or commits with no new objects). The fix: Always ensure the commit references at least one new blob object — uploading a file via Contents API guarantees this, while creating an empty commit from the current tree does not.

Multi-Source News Aggregation Pattern

For sites that auto-fetch and display content from external APIs:

  1. Sources: Hacker News (firebaseio.com), GitHub Trending (gitterapp.com), arXiv API (export.arxiv.org)
  2. Dedup by URL: Maintain existing_urls set to avoid duplicates across runs
  3. Retention: Keep N days (default 30) of content; items older than cutoff are pruned on each run
  4. Merging: Read existing data.js, parse items within retention window, merge new items

Key implementation:

# Load existing items from data.js
day_blocks = re.findall(r"day:\s*'([\d-]+)',\s*items:\s*\[(.*?)\]", existing_raw, re.DOTALL)
# Parse each item's fields (title_en, title_zh, title_ja, url, heat, source, time, day, tags)
# Filter by cutoff date
# Merge new items checking existing_urls
# Sort by day desc, then time desc
# Write merged data.js

Auto-Translate zh/ja/en for Static Sites

For auto-fetched content where manual translation isn't possible:

  1. Glossary approach: Build a dictionary mapping English terms → zh/ja translations (~80+ terms covering companies, concepts, products)
  2. Apply longest-match-first: Sort glossary by key length descending to avoid partial-match errors
  3. Data structure: Each item stores title_en, title_zh, title_ja; the build_data_js function generates zh: {title, desc}, ja: {title, desc}, en: {title, desc} for each item
  4. UI i18n: The site's JavaScript reads item[currentLang] to show the correct language
GLOSSARY = {
    "machine learning": {"zh": "机器学习", "ja": "機械学習"},
    "large language model": {"zh": "大语言模型", "ja": "大規模言語モデル"},
    # ... 80+ entries
}

Date Navigation Module

A UI pattern for browsing content by date on a static site:

  • Date picker bar: Horizontal scroll of date chips (全部, 6月23日, 6月22日...)
  • Prev/Next arrows: Navigate between available dates
  • "Today" button: Jump back to current day
  • "All" button: Show all dates
  • URL hash: #featured, #trending, #daily for deep linking

Implementation in main.js:

  • selectedDate state variable ('all' or 'YYYY-MM-DD')
  • renderDates() builds the date chip bar from NEWS_DATA days
  • renderNews() filters by selectedDate
  • navigateDate(dir) moves through sorted unique dates
  • Language-aware date formatting via DATE_FORMAT[currentLang]

Three-View System

The site supports three content views switchable via nav tabs:

ViewFunctionImplementation
Featured (精选)All items grouped by dayDefault view, per-day headers
Trending (热门)All items sorted by heat descCollects all items, sorts, adds 🥇🥈🥉 medals
Daily (AI日报)Only today's itemsFilters by day === today

MSYS/Windows Git TLS Issues

On Windows Git Bash (MSYS), git push may hang or fail with schannel: remote party requests renegotiation. Workarounds:

  • Use the Contents API (above) instead of git
  • Or configure git to use OpenSSL: git config --global http.sslBackend openssl
  • Or use SSH instead of HTTPS

Theme-Aware Logo (Dark/Light SVG)

For static sites with theme switching: create two SVG logo files (logo.svg for dark, logo-light.svg for light) and swap the <img src> via JavaScript when the theme toggle fires. See references/theme-aware-logo.md for design rules and JS implementation.

Reference Files

  • scripts/deploy_contents_api.py — Ready-to-run deploy script (explicit file list, handles create+update, enables Pages)
  • templates/fetch_news_template.py — Complete, runnable template for auto-fetching AI news from HN + arXiv, translating to zh/ja/en via glossary, and maintaining a 30-day retention window. Designed for GitHub Actions (stdlib only — no pip install needed).
  • references/i18n-static-site.md — Multi-language static site architecture
  • references/auto-update-workflow.md — Scheduled content auto-update via GitHub Actions
  • references/auto-translate-glossary.md — Glossary-based zh/ja/en translation for auto-fetched content
  • references/date-navigation-module.md — Date-based browsing UI (day picker, prev/next, "today" button)
  • references/news-aggregator-pattern.md — Multi-source news fetching, dedup, 30-day retention
  • references/classify-tags-16-categories.md — Auto-classification of AI news into 16 scientific categories with keyword triggers and CSS tag colors
  • references/token-and-windows-workarounds.md — Token revocation prevention, interactive token input patterns, Windows/MSYS TLS workarounds, fine-grained PAT limitations
  • references/card-design-patterns.md — Visual card design patterns: compact layout with source header, heat score, tags below title (aihot.virxact.com style)
  • references/glassmorphism-card-style.md — Active Theory inspired glass card style: backdrop-filter blur, gradient indicator bar, gradient text
  • references/daily-page-pattern.md — AI Daily page: sidebar date list by month, numbered categorized sections, prev/next day navigation
  • references/svg-glow-effects-logo.md — SVG neon/glow effects for logo icons: feGaussianBlur filter recipes, radar-style glow patterns, light/dark theme adaptation

Site Rename Pattern

When renaming a static site, updates are needed in all of these locations across every HTML file:

LocationWhat to change
<title>Page title
<meta name="description">Description text
<link rel="icon">Favicon path (if icon changed)
Logo <img> alt textalt="SiteName"
Logo <span> textDisplayed site name
Hero <h1>Main heading
Footer section headinge.g. <h4>📡 AI Radar</h4>
Footer descriptionAny branded text

Check all HTML files (index.html, about.html, etc.) for hardcoded references.

Pitfalls

  • Token revocation: GitHub auto-revokes tokens that appear in chat messages. Never paste tokens in chat — write them to files directly, or use interactive read -s prompts in the terminal. See references/token-and-windows-workarounds.md.
  • Interactive token input: The read -s bash command lets users paste tokens directly into the terminal without them appearing in chat history. Pattern:
    echo -n "🔑 Enter token: "
    read -s TOKEN
    echo ""
    # Then use $TOKEN for auth
    
  • Token account mismatch: The token owner must be the repo owner OR a collaborator with write access. A token from UserA cannot push to UserB/repo without UserA being added as a collaborator. Check with: GET /repos/{owner}/{repo} → check permissions.push.
  • Fine-grained PAT limitations: github_pat_ tokens may fail on Git Data API endpoints (/git/refs PATCH returns 404 or "Object does not exist"). Prefer classic ghp_ tokens for automated deployment.
  • File path encoding: Use urllib.parse.quote() for API paths with special characters (spaces, Unicode, dots)
  • Missing .nojekyll: Always include .nojekyll file for non-Jekyll sites
  • Branch name: Default may be master not main — check with GET /repos/{owner}/{repo}
  • Explicit file list: Prefer listing files explicitly in the deploy script rather than using os.walk — this avoids accidentally uploading token files, .git/ contents, or other sensitive data
  • 100% upload ≠ 100% deployment: The GitHub Pages CDN caches aggressively. After uploading via Contents API, the CDN may continue serving old content even after Pages reports "built" status. Required steps:
    1. After uploading all files, trigger a Pages rebuild (empty commit or wait for auto-build)
    2. Add version query params (?v=TIMESTAMP) to script/link hrefs in HTML to force browser cache bust
    3. Wait 1-3 minutes — the Fastly CDN typically refreshes within this window
    4. If old content persists, check the actual files on GitHub via API (GET /contents/path) — the HTML itself may be correct but cached at the CDN level
    5. The version param trick only works if the HTML itself is fresh — a chicken-and-egg problem when the HTML is cached. Create an empty commit after the HTML deploy to bust the HTML cache first.
  • Tool timeout behavior: In the Hermes environment, execute_code and terminal tools may get blocked with "timed out without user response" after a period of user inactivity. If a long-running operation (deploy, wait, build) is in progress and the user doesn't respond, subsequent tool calls are blocked. Mitigation: prefer shorter timeouts with polling patterns, or use terminal(background=True, notify_on_complete=True) for long operations.
  • Python version mismatch on Windows: System python3 may point to Python 3.14 while uv-managed environments use Python 3.11. If python3 deploy.py times out from terminal, try running via execute_code (uv's Python 3.11) which may have more reliable SSL handling.
  • Stale test files cause Pages build failures: Leftover files from earlier testing (e.g., test, test-workflow.yml) can cause GitHub Pages builds to fail with a generic "Page build failed." error and status errored. If Pages continuously fails:
    1. List files in the repo via the HEAD commit's git tree: GET /repos/{owner}/{repo}/git/trees/{HEAD_TREE_SHA} — the /contents/ endpoint may not list all files
    2. Delete non-essential files via Contents API DELETE with each file's SHA
    3. Re-upload all core site files (index.html, JS, CSS) to trigger a new build
    4. Verify with GET /pages/builds?per_page=1 — should show "status": "built"
  • Pages status "errored" recovery: When GET /pages/builds shows consistently errored with "message": "Page build failed." but no specific error message:
    1. Remove non-essential files from the repo root
    2. Ensure .nojekyll is present
    3. Push a new commit to trigger a fresh build
    4. Verify with GET /pages — status should change from errored to built within 2 minutes
  • Tool timeout on user inactivity: In the Hermes environment, execute_code and terminal tools may get blocked with "timed out without user response" after a period of user inactivity. If a long-running operation (deploy, wait, build) is in progress and the user doesn't respond, subsequent tool calls are blocked. Mitigation: prefer shorter timeouts with polling patterns, or use terminal(background=True, notify_on_complete=True) for long operations.
  • Multi-source news fetcher expansion: When adding sources to fetch_news.py, both international and Chinese domestic sources should be included. Example pattern: [get_hackernews, get_github_trending, get_arxiv, get_huggingface, get_techcrunch, get_36kr, get_qbitai]. Each source function should handle its own exceptions and return a list of item dicts. Items are deduped by URL across all sources.

Individual skills in this repo

This repo contains 1 individual skill — each has its own dedicated page.

Related Skills