repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/skills/gh-cli/scripts/gh_pages_deploy.mjs

Raw
File outline
#!/usr/bin/env node
import { spawnSync } from "node:child_process";
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

function arg(name, def) {
	const i = process.argv.indexOf(name);
	return i === -1 ? def : process.argv[i + 1];
}
function has(name) {
	return process.argv.includes(name);
}
function json(x) {
	return JSON.stringify(x, null, 2);
}
function msg(s, style = "info") {
	return `${{ info: "ℹ", success: "✓", error: "✗", warning: "⚠" }[style] ?? ""} ${s}`;
}
function checkAuth() {
	const r = spawnSync("gh", ["auth", "status", "--show-token"], {
		encoding: "utf8",
	});
	if (r.status !== 0 || r.error) return [false, []];
	const scopes = [];
	for (const line of r.stdout.split("\n")) {
		const m = /:\s*(\w+)/.exec(line);
		if (line.toLowerCase().includes("scope") && m) scopes.push(m[1]);
	}
	return [true, scopes];
}
class Pages {
	constructor(repo, dryRun = false, jsonOut = false) {
		this.repo = repo;
		this.dryRun = dryRun;
		this.jsonOut = jsonOut;
		const [ok, scopes] = checkAuth();
		if (!ok) {
			const e = {
				error: "GitHub CLI is not authenticated",
				solution: "Run 'gh auth login' to authenticate",
			};
			if (jsonOut) console.log(json(e));
			else {
				console.error(msg("GitHub CLI is not authenticated.", "error"));
				console.error("Run 'gh auth login' to authenticate.");
			}
			process.exit(1);
		}
		if (!scopes.includes("repo") && jsonOut)
			console.log(
				json({
					warning: "Missing 'repo' scope",
					scopes,
					may_not_work: "Private repo operations may fail",
				}),
			);
	}
	api(endpoint, method = "GET", data, check = true) {
		if (this.dryRun && method !== "GET") {
			console.error(`[DRY RUN] Would execute: ${method} ${endpoint}`);
			if (data) console.error(`[DRY RUN] With data: ${JSON.stringify(data)}`);
			return [0, { dry_run: true, endpoint, method }];
		}
		const args = [
			"api",
			"-X",
			method,
			"-H",
			"Accept: application/vnd.github+json",
			"-H",
			"X-GitHub-Api-Version: 2022-11-28",
			endpoint,
		];
		if (data)
			for (const [k, v] of Object.entries(data))
				if (typeof v === "object" && v)
					for (const [sk, sv] of Object.entries(v))
						args.push("-f", `${k}[${sk}]=${sv}`);
				else args.push("-f", `${k}=${typeof v === "boolean" ? String(v) : v}`);
		const r = spawnSync("gh", args, {
			encoding: "utf8",
			timeout: 30000,
			maxBuffer: 10 * 1024 * 1024,
		});
		let body = {};
		if (r.stdout.trim()) {
			try {
				body = JSON.parse(r.stdout);
			} catch {
				body = { raw: r.stdout };
			}
		}
		if (r.status !== 0 && check)
			throw new Error(
				`Failed to execute gh command: ${r.stderr || JSON.stringify(body)}`,
			);
		return [r.status ?? 1, body];
	}
	enable(branch = "main", path = "/", build_type = "workflow", https = true) {
		if (!this.jsonOut) {
			console.log(`Enabling GitHub Pages for ${this.repo}...`);
			console.log(`  Branch: ${branch}`);
			console.log(`  Path: ${path}`);
			console.log(`  Build type: ${build_type}`);
		}
		const endpoint = `/repos/${this.repo}/pages`;
		const [status, res] = this.api(
			endpoint,
			"POST",
			{ source: { branch, path }, build_type },
			false,
		);
		if (status === 0 || res.dry_run) {
			const out = {
				status: res.dry_run ? "dry_run" : "success",
				action: "pages_enabled",
				repository: this.repo,
				config: { branch, path, build_type, https_enforced: https },
				dry_run: !!res.dry_run,
			};
			if (this.jsonOut) console.log(json(out));
			else
				console.log(
					msg(
						res.dry_run
							? "GitHub Pages would be enabled (dry-run)"
							: "GitHub Pages enabled successfully!",
						"success",
					),
				);
			if (https && !this.dryRun)
				this.api(endpoint, "PUT", { https_enforced: true }, false);
			return res;
		}
		if (status === 422) return this.status();
		const out = { status: "error", error: res.message ?? "Unknown error" };
		if (this.jsonOut) console.log(json(out));
		else console.error(msg(`Failed to enable Pages: ${out.error}`, "error"));
		return res;
	}
	status() {
		if (!this.jsonOut)
			console.log(`Checking GitHub Pages status for ${this.repo}...`);
		const [status, res] = this.api(
			`/repos/${this.repo}/pages`,
			"GET",
			undefined,
			false,
		);
		if (status === 0) {
			const out = {
				status: "enabled",
				repository: this.repo,
				url: res.html_url ?? "N/A",
				pages_status: res.status ?? "N/A",
				build_type: res.build_type ?? "N/A",
				source: res.source ?? {},
				https_enforced: res.https_enforced ?? false,
				custom_domain: res.cname,
			};
			if (this.jsonOut) console.log(json(out));
			else {
				console.log(msg("GitHub Pages is enabled:", "success"));
				console.log(`  URL: ${out.url}`);
				console.log(`  Status: ${out.pages_status}`);
				console.log(`  Build type: ${out.build_type}`);
				console.log(`  Source branch: ${out.source.branch ?? "N/A"}`);
				console.log(`  Source path: ${out.source.path ?? "N/A"}`);
				console.log(`  HTTPS enforced: ${out.https_enforced}`);
				if (out.custom_domain)
					console.log(`  Custom domain: ${out.custom_domain}`);
			}
		} else if (this.jsonOut)
			console.log(
				json({
					status: "disabled",
					repository: this.repo,
					message: "GitHub Pages is not enabled",
				}),
			);
		else
			console.error(
				msg("GitHub Pages is not enabled for this repository.", "warning"),
			);
		return res;
	}
	rebuild() {
		if (!this.jsonOut) console.log(`Triggering rebuild for ${this.repo}...`);
		const [status, res] = this.api(
			`/repos/${this.repo}/pages/builds`,
			"POST",
			undefined,
			false,
		);
		if (status === 0 || res.dry_run) {
			const out = {
				status: "triggered",
				repository: this.repo,
				build_url: res.url,
			};
			if (this.jsonOut) console.log(json(out));
			else {
				console.log(msg("Build triggered successfully!", "success"));
				console.log(`  Status: ${res.status ?? "N/A"}`);
				if (res.url) console.log(`  Build URL: ${res.url}`);
			}
		} else if (this.jsonOut)
			console.log(
				json({ status: "error", error: res.message ?? "Unknown error" }),
			);
		else
			console.error(
				msg(
					`Failed to trigger build: ${res.message ?? "Unknown error"}`,
					"error",
				),
			);
		return res;
	}
	latest() {
		const [status, res] = this.api(
			`/repos/${this.repo}/pages/builds/latest`,
			"GET",
			undefined,
			false,
		);
		if (status === 0) {
			const out = {
				status: res.status ?? "N/A",
				commit: res.commit ?? "N/A",
				created_at: res.created_at,
				error: res.error ?? {},
			};
			if (this.jsonOut) console.log(json(out));
			else {
				console.log("\nLatest build:");
				console.log(`  Status: ${out.status}`);
				console.log(`  Commit: ${out.commit}`);
				if (out.created_at) console.log(`  Created: ${out.created_at}`);
				if (out.error?.message) console.log(`  Error: ${out.error.message}`);
			}
		}
		return res;
	}
}
function createWorkflow(output = ".github/workflows/pages.yml", force = false) {
	if (existsSync(output) && !force) {
		const out = {
			status: "skipped",
			reason: "file_exists",
			path: resolve(output),
		};
		console.log(json(out));
		return out;
	}
	const content = `name: Deploy to GitHub Pages

on:
  push:
    branches: ["main"]
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Setup Pages
        uses: actions/configure-pages@v5
      - name: Build site
        run: |
          mkdir -p _site
          cp -r * _site/ 2>/dev/null || true
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: '_site'
  deploy:
    environment:
      name: github-pages
      url: \${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4
`;
	mkdirSync(dirname(output), { recursive: true });
	writeFileSync(output, content);
	const out = { status: "created", path: resolve(output) };
	console.log(json(out));
	if (!process.cwd().endsWith("gh-cli"))
		console.log(
			"\nNext steps:\n1. Customize the 'Build site' step with your build commands\n2. Ensure the correct files are copied to _site/\n3. Commit and push this workflow file to your repository\n4. Enable GitHub Pages with 'GitHub Actions' as the source",
		);
	return out;
}
function main() {
	const cmd = process.argv.find((a) =>
		["enable", "status", "rebuild", "create-workflow"].includes(a),
	);
	if (!cmd) {
		console.error(
			"Usage: gh_pages_deploy.mjs <enable|status|rebuild|create-workflow>",
		);
		return 1;
	}
	const dry = has("--dry-run"),
		jout = has("--json");
	if (cmd === "create-workflow") {
		createWorkflow(arg("--output"), has("--force"));
		return 0;
	}
	const repo = process.argv[process.argv.indexOf(cmd) + 1];
	if (!repo) throw new Error("repo required");
	const p = new Pages(repo, dry, jout);
	if (cmd === "enable") {
		p.enable(
			arg("--branch", "main"),
			arg("--path", "/"),
			arg("--build-type", "workflow"),
			!has("--no-https"),
		);
		if (arg("--build-type", "workflow") === "workflow" && !jout)
			console.log(
				"\nTip: Create a deployment workflow with:\n   gh pages create-workflow",
			);
	} else if (cmd === "status") {
		p.status();
		if (has("--build-info")) p.latest();
	} else if (cmd === "rebuild") p.rebuild();
	return 0;
}
export const __test = {
	createWorkflow,
	json,
	msg,
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
	try {
		process.exit(main());
	} catch (e) {
		console.log(json({ status: "error", error: e.message }));
		process.exit(1);
	}
}