brainstorming
brainstorming
You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).
github-apiIntegrates with the GitHub REST API and GraphQL API via PyGithub and Octokit to manage repositories, issues, pull requests, Actions workflows, and Copilot metrics.
Independent GitHub snapshot · Automated classification · Original documentation governs
name: github-api description: Integrates with the GitHub REST API and GraphQL API via PyGithub and Octokit to manage repositories, issues, pull requests, Actions workflows, and Copilot metrics. license: MIT compatibility: opencode metadata: version: "1.0.0" domain: coding triggers: github api, octokit, pygithub, github rest api, github graphql, manage repositories, github actions, pull request automation archetypes:
Integrates with GitHub's REST API v3 and GraphQL API v4 to automate repository management, issue tracking, pull request workflows, Actions pipelines, and Copilot usage analytics. Use PyGithub for Python projects or Octokit for JavaScript/TypeScript projects.
github.Auth.Token() for PyGithub or new Octokit({ auth }) for Octokit.jsget_paginated() or for async of iteratorsgithub.GithubException or octokit.RequestErrorget_rate_limit() before bulk operationsGithub(auth=Auth.Token(token)) or new Octokit({ auth }). Checkpoint: Verify the token has the correct scopes (repo, workflow, admin:org) for your operations.g.get_repo("owner/repo") or octokit.rest.repos.get({ owner, repo }). Checkpoint: Confirm the repository exists and is accessible with a 200 response.repo.get_issues(state='all') or octokit.paginate() for list endpoints. Checkpoint: Ensure you consume all pages, not just the first page (default 30 items).GithubException or RequestError, inspect status codes (401=bad auth, 403=rate limit, 404=not found, 422=validation), and implement exponential backoff for 503s. Checkpoint: Log the request ID from error headers for debugging.import os
from github import Github, Auth
def sync_fork(
upstream_owner: str,
upstream_repo: str,
fork_owner: str | None = None,
) -> dict:
"""Sync a fork with its upstream repository using PyGithub.
Args:
upstream_owner: Owner of the upstream repository.
upstream_repo: Name of the upstream repository.
fork_owner: Owner of the fork (defaults to authenticated user).
Returns:
Dict with merge status and commit SHA.
Raises:
GithubException: If authentication fails or repo is unreachable.
"""
token = os.environ["GITHUB_TOKEN"]
g = Github(auth=Auth.Token(token))
upstream = g.get_repo(f"{upstream_owner}/{upstream_repo}")
fork = g.get_repo(f"{fork_owner or g.get_user().login}/{upstream_repo}")
# Get the default branch from upstream
default_branch = upstream.default_branch
upstream_branch = upstream.get_branch(default_branch)
fork_branch = fork.get_branch(default_branch)
if upstream_branch.commit.sha == fork_branch.commit.sha:
return {"status": "already_synced", "sha": fork_branch.commit.sha}
# Merge upstream into fork
merge_result = fork.merge(upstream_branch.commit.sha)
return {
"status": "merged" if merge_result.merged else "conflict",
"sha": merge_result.sha,
"message": merge_result.message,
}
import os
import requests
def trigger_workflow(
owner: str,
repo: str,
workflow_file: str,
ref: str = "main",
inputs: dict | None = None,
) -> int:
"""Trigger a GitHub Actions workflow_dispatch event.
Returns the workflow run ID if triggered successfully.
Raises:
requests.HTTPError: If the API returns a non-204 status.
"""
token = os.environ["GITHUB_TOKEN"]
url = f"https://api.github.com/repos/{owner}/{repo}/actions/workflows/{workflow_file}/dispatches"
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github.v3+json",
"User-Agent": "agent-skill-router/1.0",
}
payload: dict = {"ref": ref}
if inputs:
payload["inputs"] = inputs
response = requests.post(url, headers=headers, json=payload)
# workflow_dispatch returns 204 No Content on success
if response.status_code != 204:
response.raise_for_status()
# Parse the Location header to extract the run ID
runs_url = f"https://api.github.com/repos/{owner}/{repo}/actions/runs"
runs_response = requests.get(
f"{runs_url}?event=workflow_dispatch&per_page=1",
headers=headers,
)
runs_response.raise_for_status()
runs_data = runs_response.json()
if runs_data["total_count"] > 0:
return runs_data["workflow_runs"][0]["id"]
msg = "Workflow was dispatched but no run ID could be resolved."
raise RuntimeError(msg)
import { Octokit } from "@octokit/rest";
/**
* Merge a pull request after posting a review comment.
*/
async function mergePrWithComment(
owner, repo, pullNumber, comment
) {
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
// Post a review comment on the PR
await octokit.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body: comment,
});
// Merge the PR using squash strategy
const result = await octokit.rest.pulls.merge({
owner,
repo,
pull_number: pullNumber,
merge_method: "squash",
});
if (result.data.merged) {
console.log(`PR #${pullNumber} merged: ${result.data.sha}`);
} else {
throw new Error(`PR merge failed: ${result.data.message}`);
}
}
# ❌ BAD — silent failure, no type hints, no context
def create_issue(repo, title):
try:
repo.create_issue(title=title, body="")
return True
except:
return False
# ✅ GOOD — typed, specific exceptions, meaningful error message
from github import GithubException
def create_issue(
repo_full_name: str,
title: str,
body: str = "",
labels: list[str] | None = None,
) -> dict:
"""Create a GitHub issue and return its URL and number.
Raises:
GithubException: With status code and error message from the API.
"""
token = os.environ["GITHUB_TOKEN"]
g = Github(auth=Auth.Token(token))
repo = g.get_repo(repo_full_name)
try:
issue = repo.create_issue(
title=title,
body=body,
labels=labels or [],
)
return {"number": issue.number, "url": issue.html_url}
except GithubException as exc:
status = exc.status
msg = exc.data.get("message", "Unknown error")
raise RuntimeError(
f"Failed to create issue in {repo_full_name}: "
f"HTTP {status} — {msg}"
) from exc
code-philosophy (5 Laws of Elegant Defense) in all logic| Skill | Purpose |
|---|---|
coding-gitlab-api | GitLab API with python-gitlab for projects/pipelines/MRs |
coding-bitbucket-api | Bitbucket Cloud API with atlassian-python-api |
coding-jenkins-api | Jenkins automation for job/build/plugin management |