跳转到第一次提交

在 Github 的 commits 页面添加一个按钮,可以跳转到 repo 的第一次提交页面

目前为 2020-06-17 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name Go To Initial Commit
  3. // @name:zh-CN 跳转到第一次提交
  4. // @namespace https://github.com/Liu233w/
  5. // @version 0.1
  6. // @description Add a button on Github commit page which allow you to nevigate to the first commit page
  7. // @description:zh-CN 在 Github 的 commits 页面添加一个按钮,可以跳转到 repo 的第一次提交页面
  8. // @author Liu233w
  9. // @license BSD 3-Clause License
  10. // @icon https://assets-cdn.github.com/pinned-octocat.svg
  11. // @match https://github.com/*/commits/*
  12. // @grant none
  13. // ==/UserScript==
  14.  
  15. (function() {
  16. 'use strict';
  17.  
  18. function openFirstCommit(args) {
  19. // args[1] is the `orgname/repo` url fragment
  20. // args[2] is the optional branch or hash
  21.  
  22. return fetch('https://api.github.com/repos/' + args[1] + '/commits?sha=' + (args[2] || ''))
  23.  
  24. // the link header has additional urls for paging
  25. // parse the original JSON for the case where no other pages exist
  26. .then(res => Promise.all([res.headers.get('link'), res.json()]))
  27.  
  28. // get last page of commits
  29. .then(results => {
  30. // results[0] is the link
  31. // results[1] is the first page of commits
  32.  
  33. if (results[0]) {
  34. // the link contains two urls in the form
  35. // <https://github.com/...>; rel=blah, <https://github.com/...>; rel=thelastpage
  36. // split the url out of the string
  37. var pageurl = results[0].split(',')[1].split(';')[0].slice(2, -1);
  38. // fetch the last page
  39. return fetch(pageurl).then(res => res.json());
  40. }
  41.  
  42. // if no link, we know we're on the only page
  43. return results[1];
  44. })
  45.  
  46. // get the last commit and extract the url
  47. .then(commits => commits.pop().html_url)
  48.  
  49. // navigate there
  50. .then(url => window.location = url);
  51. }
  52.  
  53. // add button
  54. var nav = document.querySelector('.file-navigation');
  55. var tempDom = document.createElement('div');
  56. tempDom.innerHTML = '<span type="button" class="btn btn-sm" title="go to the initial(first) commit">initial commit</button>';
  57. var button = tempDom.firstChild;
  58. button.addEventListener('click', function () {
  59. openFirstCommit(window.location.pathname.match(/\/([^\/]+\/[^\/]+)(?:\/tree\/([^\/]+))?/));
  60. });
  61. nav.appendChild(button);
  62. button.previousElementSibling.style.display = "inline"
  63. })();