title | date | categories | |
---|---|---|---|
Github_goToAnyCommit.Js |
2023-11-23 |
|
how to add bookmarklet in chrome
import { getCurrentTab, showLoading } from "./helpers/utils.js"; export default { icon: '', name: { en: "Go to any commit", en: "Go to any commit", }, description: { en: "Go to any commit of github repo. Included first commit.", en: "Go to commit any of the github reposits. Including the first commit.", }, onClickExtension: async () => { let { closeLoading, setLoadingText } = showLoading("Pending url input..."); try { let tab = await getCurrentTab(); let url = prompt("Enter github repo link: ", tab.url); if (url == null) return; if (!url.includes("github.com")) throw Error( "Link is not properly formatted.\nLink e.g. https://github.com/HoangTran0410/useful-script " ); let repoName = shared.getRepoNameFromUrl(url); let [user, repo] = repoName.split("/"); setLoadingText("Counting the number of commits..."); let totalCommits = await shared.getTotalCommitCount(user, repo); setLoadingText("Pending selection..."); let index; while (true) { index = prompt( 'Yes ${totalCommits} commits in '${repo}' of ${user} .\n\n ' + 'Enter the commit you want to see (1-${totalCommits}):\n' + ' (1 is the first commit)', 1 ); if (index == null) return; if (index < 1 || index > totalCommits) alert( 'Invalid selection (1-${totalCommits}). Please select again.' ); else break; } setLoadingText("Looking for a commit link..."); let firstCommit = await shared.getCommitAtIndex( user, repo, totalCommits – index + 1 ); if (firstCommit.html_url) window.open(firstCommit.html_url); else throw new Error("Link not found."); } catch (e) { alert("ERROR: " + e); } finally { closeLoading(); } }, }; export const shared = { // Idea from: https://github.com/FarhadG/init // https://github.com/HoangTran0410/useful-script => repoName = HoangTran0410/useful-script getRepoNameFromUrl(url) { let pathName = new URL(url).pathname; let [repoName, branchOrHash] = pathName.match(/\/([^\/]+\/[^\/]+)(?:\/tree\/([^\/]+)))? /) || []; return repoName.slice(1); }, getTotalCommitCount: async(user, repo) => { let res = await fetch( 'https://api.github.com/repos/${user}/${repo}/commits?per_page=1 ' ); let linkInHeader = res.headers.get("link"); let commitCount = linkInHeader.match(/&page=(\d+)>; rel="last"/)?. [1]; return Number(commitCount); }, getCommitAtIndex: async(user, repo, index) => { let res = await fetch( 'https://api.github.com/repos/${user}/${repo}/commits?per_page=1&page=${index} ' ); let json = await res.json(); return json[0]; }, };