Add Sourcegraph Button to GitHub

Add a 'Sourcrgraph' Button on GitHub repository & file page.

Verze ze dne 11. 11. 2019. Zobrazit nejnovější verzi.

  1. // ==UserScript==
  2. // @name Add Sourcegraph Button to GitHub
  3. // @description Add a 'Sourcrgraph' Button on GitHub repository & file page.
  4. // @version 1
  5. // @grant none
  6. // @inject-into auto
  7. // @supportURL https://github.com/whtsky/userscripts/issues
  8. // @match https://github.com/*
  9. // @namespace https://greatest.deepsurf.us/users/164794
  10. // ==/UserScript==
  11.  
  12. function goToSourcegraph(event) {
  13. event.preventDefault()
  14. var pats = [
  15. [
  16. '^/([^/]+)/([^/]+)/tree/([^/]+)$',
  17. '/github.com/$1/$2@$3',
  18. '^/github.com/([^/]+)/([^/@]+)@([^/]+)$',
  19. '/$1/$2/tree/$3',
  20. ],
  21. [
  22. '^/([^/]+)/([^/]+)/tree/([^/]+)/(.+)$',
  23. '/github.com/$1/$2@$3/-/tree/$4',
  24. '^/github.com/([^/]+)/([^/@]+)@([^/]+)/-/tree/(.+)$',
  25. '/$1/$2/tree/$3/$4',
  26. ],
  27. ['^/([^/]+)/([^/]+)/blob/([^/]+)/(.+)$', '/github.com/$1/$2@$3/-/blob/$4', '', ''],
  28. ['^/([^/]+)/([^/]+)$', '/github.com/$1/$2', '^/github.com/([^/]+)/([^/]+)$', '/$1/$2'],
  29. ['^/([^/]+)$', '/$1', '^/([^/]+)$', '/$1'],
  30. ]
  31. var pathname = window.location.pathname
  32. for (var i = 0; i < pats.length; i++) {
  33. var pat = pats[i]
  34. var r, pathname2
  35. if (window.location.hostname === 'github.com') {
  36. if (pat[0] === '') {
  37. continue
  38. }
  39. r = new RegExp(pat[0])
  40. if (pathname.match(r)) {
  41. pathname2 = pathname.replace(r, pat[1])
  42. window.location = 'https://sourcegraph.com' + pathname2
  43. return
  44. }
  45. } else {
  46. if (pat[2] === '') {
  47. continue
  48. }
  49. r = new RegExp(pat[2])
  50. if (pathname.match(r)) {
  51. pathname2 = pathname.replace(r, pat[3])
  52. window.location = 'https://github.com' + pathname2
  53. return
  54. }
  55. }
  56. }
  57. alert('Unable to jump to Sourcegraph (no matching URL pattern).')
  58. }
  59.  
  60. function createButton() {
  61. if (document.querySelector('#userscript__sourcegraph')) {
  62. return
  63. }
  64. const targetBtn = document.querySelector('#raw-url') || document.querySelector('a.BtnGroup-item')
  65. if (targetBtn) {
  66. const newBtn = targetBtn.cloneNode(false)
  67. newBtn.setAttribute('id', 'userscript__sourcegraph')
  68. newBtn.setAttribute('class', 'btn btn-sm BtnGroup-item')
  69. newBtn.textContent = 'Sourcegraph'
  70. newBtn.href = ''
  71. newBtn.addEventListener('click', goToSourcegraph)
  72. targetBtn.parentNode.insertBefore(newBtn, targetBtn)
  73. }
  74. }
  75.  
  76. const observer = new MutationObserver(function() {
  77. observer.disconnect()
  78. createButton()
  79. observer.observe(document.body, { childList: true, subtree: true })
  80. })
  81. observer.observe(document.body, { childList: true, subtree: true })
  82.  
  83. createButton()