Go To Initial Commit

Add a button on Github commit page which allow you to nevigate to the first commit page

当前为 2018-02-07 提交的版本,查看 最新版本

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