Raw2Repo

将不同代码托管平台(GitHub、Gitee、GitCode、GitLab)上的 raw URL 转换为相应的 blob/repo URL

  1. // ==UserScript==
  2. // @name Raw2Repo
  3. // @namespace https://github.com/rickhqh
  4. // @version 1.51
  5. // @description 将不同代码托管平台(GitHub、Gitee、GitCode、GitLab)上的 raw URL 转换为相应的 blob/repo URL
  6. // @author rickhqh
  7. // @match http*://raw.githubusercontent.com/*
  8. // @include *://raw.githubusercontent.com/*
  9. // @match http*://gitee.com/*/raw/*
  10. // @match http*://raw.gitcode.com/*
  11. // @match http*://gitlab.com/*/raw/*
  12. // @license MIT
  13. // @icon https://greasyfork.s3.us-east-2.amazonaws.com/0cz0a0mj7wd9wcpeoukisaynmgzg
  14. // ==/UserScript==
  15.  
  16. (function () {
  17. 'use strict';
  18.  
  19. const transformRaw2Repo = (rawURL) => {
  20. // GitHub 格式匹配
  21. const githubRegex = /^https:\/\/raw\.githubusercontent\.com\/([^\/]+)\/([^\/]+)\/.+/;
  22. const githubMatch = rawURL.match(githubRegex);
  23.  
  24. // Gitee 格式匹配
  25. const giteeRegex = /^https:\/\/gitee\.com\/([^\/]+)\/([^\/]+)\/raw\/([^\/]+)\/(.+)$/;
  26. const giteeMatch = rawURL.match(giteeRegex);
  27.  
  28. // GitCode 格式匹配
  29. const gitCodeRegex = /^https:\/\/raw\.gitcode\.com\/([^\/]+)\/([^\/]+)\/raw\/([^\/]+)\/(.+)$/;
  30. const gitCodeMatch = rawURL.match(gitCodeRegex);
  31.  
  32. //Gitlab 格式匹配
  33. const gitlabRegex = /^https:\/\/gitlab\.com\/([^\/]+)\/([^\/]+)\/-\/raw\/([^\/]+)\/(.+?)(?:\?.*)?$/;
  34. const gitlabMatch = rawURL.match(gitlabRegex);
  35.  
  36. // 根据匹配的结果构建新的 URL
  37. if (githubMatch) {
  38. const [, githubUser, githubRepo] = githubMatch;
  39. return `https://github.com/${githubUser}/${githubRepo}`;
  40. } else if (giteeMatch) {
  41. const [, giteeUser, giteeRepo, giteeBranch, giteePath] = giteeMatch;
  42. return `https://gitee.com/${giteeUser}/${giteeRepo}/blob/${giteeBranch}/${giteePath}`;
  43. } else if (gitCodeMatch) {
  44. const [, gitCodeUser, gitCodeRepo, gitCodeBranch, gitCodePath] = gitCodeMatch;
  45. return `https://gitcode.com/${gitCodeUser}/${gitCodeRepo}/blob/${gitCodeBranch}/${gitCodePath}`;
  46. } else if (gitlabMatch) {
  47. const [, gitlabUser, gitlabRepo, gitlabBranch, gitlabPath] = gitlabMatch;
  48. return `https://gitlab.com/${gitlabUser}/${gitlabRepo}/-/blob/${gitlabBranch}/${gitlabPath}`;
  49. } else {
  50. // 如果都不匹配,返回原始 URL
  51. return rawURL;
  52. }
  53. };
  54.  
  55. function openRepo() {
  56. // 创建跳转按钮
  57. const jumpButton = document.createElement('button');
  58. jumpButton.textContent = 'Jump to Repo';
  59. jumpButton.style.position = 'fixed';
  60. jumpButton.style.top = '10px';
  61. jumpButton.style.right = '10px';
  62. jumpButton.addEventListener('click', function () {
  63. window.location.href = transformRaw2Repo(window.location.href);
  64. });
  65.  
  66. // 将按钮插入到页面中
  67. document.body.appendChild(jumpButton);
  68. }
  69.  
  70. // 在页面加载后等待0.1秒再执行跳转
  71. setTimeout(openRepo, 100);
  72. })();