code icon Code

List GitHub Pull Requests

Fetch pull requests from a GitHub repository

Source Code

const [owner, repo, state = "open", per_page = "30", page = "1"] = process.argv.slice(2);

const token = process.env.GITHUB_TOKEN || "PLACEHOLDER_TOKEN";

async function listPRs() {
  const params = new URLSearchParams({
    state,
    per_page,
    page,
    sort: "created",
    direction: "desc",
  });

  const url = `https://api.github.com/repos/${owner}/${repo}/pulls?${params}`;
  
  console.log(`Fetching pull requests from ${owner}/${repo} (state: ${state}, page: ${page})...`);

  const response = await fetch(url, {
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/vnd.github+json",
      "X-GitHub-Api-Version": "2022-11-28",
    },
  });

  if (!response.ok) {
    const error = await response.json();
    console.error("ERROR: GitHub API request failed.");
    console.error(`  Status: ${response.status}`);
    console.error(`  Message: ${error.message || response.statusText}`);
    console.error("  Check that the repository exists and you have access.");
    process.exit(1);
  }

  const remaining = response.headers.get("X-RateLimit-Remaining");
  if (remaining && parseInt(remaining) < 100) {
    console.log(`โš ๏ธ Rate limit warning: ${remaining} requests remaining`);
  }

  const prs = await response.json();

  const fs = await import("fs");
  fs.writeFileSync("session/prs.json", JSON.stringify(prs, null, 2));

  console.log(`Found ${prs.length} pull requests, wrote to session/prs.json`);
  
  if (prs.length > 0) {
    console.log("\nRecent PRs:");
    prs.slice(0, 5).forEach(pr => {
      const status = pr.draft ? "๐Ÿ“ draft" : pr.merged_at ? "๐ŸŸฃ merged" : pr.state === "open" ? "๐ŸŸข open" : "๐Ÿ”ด closed";
      console.log(`  #${pr.number}: ${pr.title} (${pr.head.ref} โ†’ ${pr.base.ref}) [${status}]`);
    });
    if (prs.length > 5) {
      console.log(`  ... and ${prs.length - 5} more`);
    }
  }
}

try {
  await listPRs();
} catch (error) {
  console.error("ERROR: Unexpected failure listing pull requests.");
  console.error(`  ${error.message}`);
  process.exit(1);
}