Last active
October 2, 2024 12:24
-
-
Save tuananh/d1ce7135e24687e90641ba5f9f5598e1 to your computer and use it in GitHub Desktop.
Go to first commit of GitHub repo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function goToFirstCommit(owner, repo) { | |
const headers = { | |
"Accept": "application/vnd.github.v3+json", | |
// Optional: Add authorization if you hit the rate limit (use a personal access token) | |
// "Authorization": "Bearer YOUR_GITHUB_TOKEN" | |
}; | |
const repoInfo = await fetch(`https://api.github.com/repos/${owner}/${repo}`, { headers }); | |
const repoData = await repoInfo.json(); | |
const defaultBranch = repoData.default_branch; | |
const branchInfo = await fetch(`https://api.github.com/repos/${owner}/${repo}/branches/${defaultBranch}`, { headers }); | |
const branchData = await branchInfo.json(); | |
const latestCommitSha = branchData.commit.sha; | |
// Step 2: Get the total number of commits in the default branch using the API for commits count | |
const commitsInfo = await fetch(`https://api.github.com/repos/${owner}/${repo}/commits?sha=${defaultBranch}&per_page=1`, { headers }); | |
const linkHeader = commitsInfo.headers.get("link"); | |
// The "last" page link in the Link header contains the total number of commits | |
let totalCommits; | |
if (linkHeader) { | |
const lastPageMatch = linkHeader.match(/&page=(\d+)>; rel="last"/); | |
totalCommits = lastPageMatch ? lastPageMatch[1] : 1; | |
} else { | |
// If there's no pagination, it means there is only one page of commits | |
totalCommits = 1; | |
} | |
console.log(`Total commits in ${defaultBranch} branch: ${totalCommits}`); | |
if (totalCommits != 1) { | |
const firstCommitURL = `https://github.com/${owner}/${repo}/commits/${defaultBranch}/?after=${latestCommitSha}+${totalCommits - 36}` | |
console.log(`First commit URL is ${firstCommitURL}`) | |
window.location.href = firstCommitURL; | |
} | |
} | |
async function main() { | |
const currentUrl = window.location.href; | |
const regex = /https:\/\/github\.com\/([^\/]+)\/([^\/]+)/; | |
const match = currentUrl.match(regex); | |
if (match) { | |
const owner = match[1]; | |
const repo = match[2]; | |
console.log(`Owner: ${owner}`); | |
console.log(`Repository: ${repo}`); | |
await goToFirstCommit(owner, repo); | |
} else { | |
console.log("Not on a GitHub repository page."); | |
} | |
} | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use this website to create bookmarklet.