GitHub Update Fork

A userscript that adds a link to update your fork

  1. // ==UserScript==
  2. // @name GitHub Update Fork
  3. // @version 0.2.0
  4. // @description A userscript that adds a link to update your fork
  5. // @license MIT
  6. // @author Rob Garrison
  7. // @namespace https://github.com/Mottie
  8. // @include https://github.com/*
  9. // @run-at document-idle
  10. // @grant none
  11. // @icon https://github.githubassets.com/pinned-octocat.svg
  12. // ==/UserScript==
  13. (() => {
  14. "use strict";
  15.  
  16. function getUpstreamBranch(compareLink, info) {
  17. // Look for "commit behind" or "commits behind"
  18. if (compareLink && info && /commits?\sbehind/.test(info.textContent)) {
  19. // forked from link text ":user/:repo"
  20. const regexp = /behind\s*(.+:[-\w.]+)/;
  21. // The match will include the sentence period because branch names may
  22. // include a version number, e.g. "user:my-branch-v1.0"
  23. const branch = (info.textContent.match(regexp) || [])[1];
  24. return branch
  25. ? branch.substring(0, branch.length - 1)
  26. : null;
  27. }
  28. return null;
  29. }
  30.  
  31. function getUserBranch() {
  32. // The branch selector may contain a truncated branch name, so use the url
  33. const path = window.location.pathname;
  34. const index = path.indexOf("/tree/");
  35. return index > -1
  36. ? path.substring(index + 6, path.length)
  37. : "master";
  38. }
  39.  
  40. function addLink(compareLink, info) {
  41. const branch = getUpstreamBranch(compareLink, info);
  42. if (branch) {
  43. const userBranch = getUserBranch();
  44. const prLink = compareLink.previousElementSibling;
  45. const link = prLink.cloneNode();
  46. // https://github.com/<FORK>/<REPO>/compare/<BRANCH>...<SOURCE>:<BRANCH>
  47. link.href = `${compareLink.href}/${userBranch}...${branch}`;
  48. link.classList.add("ghuf-update-link");
  49. link.appendChild($("svg", prLink).cloneNode(true));
  50. link.appendChild(document.createTextNode(" Update fork"));
  51. prLink.insertAdjacentElement("beforebegin", link);
  52. }
  53. }
  54.  
  55. function init() {
  56. const compareLink = $("a[href*='pull/new'] + a[href$='/compare']");
  57. const info = compareLink?.closest(".Box")?.firstElementChild;
  58. if (compareLink && info) {
  59. addLink(compareLink, info);
  60. }
  61. }
  62.  
  63. function $(str, el = document) {
  64. return el.querySelector(str);
  65. }
  66.  
  67. document.addEventListener("pjax:end", init);
  68. init();
  69.  
  70. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址