code icon Code

List GitHub Repository Branches

Fetch list of branches in a repository

Source Code

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

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

async function listBranches() {
  const params = new URLSearchParams({ per_page });
  const url = `https://api.github.com/repos/${owner}/${repo}/branches?${params}`;
  
  console.log(`Fetching branches for ${owner}/${repo}...`);

  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 branches = await response.json();

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

  console.log(`Found ${branches.length} branches, wrote to session/branches.json`);
  
  if (branches.length > 0) {
    console.log("\nBranches:");
    branches.slice(0, 10).forEach(branch => {
      const protection = branch.protected ? "๐Ÿ”’" : "";
      console.log(`  ${protection}${branch.name}`);
    });
    if (branches.length > 10) {
      console.log(`  ... and ${branches.length - 10} more`);
    }
  }
}

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