Last active
May 17, 2023 10:35
-
-
Save jorgelbg/8a5d12f39009207becec4da452b553c7 to your computer and use it in GitHub Desktop.
UserScript for rewriting pkg.go.dev links to always use sourcegraph.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name pkg.go.dev links to sourcegraph | |
// @namespace https://jorgelbg.me/ | |
// @version 0.1 | |
// @description Translate all the cs.opensource.google and github.com links to sourcegraph.com on pkg.go.dev. | |
// @author Jorge Luis Betancourt <[email protected]> | |
// @match https://pkg.go.dev/* | |
// @icon https://sourcegraph.com/.assets/img/sourcegraph-mark.svg | |
// @require https://openuserjs.org/src/libs/sizzle/GM_config.js | |
// @grant GM_getValue | |
// @grant GM_setValue | |
// ==/UserScript== | |
(function () { | |
"use strict"; | |
let sourcegraphLink = | |
"https://sourcegraph.com/github.com/$__repo@$__tag/-/blob/$__path?L$__line"; | |
let googleRegex = new RegExp( | |
/cs\.opensource\.google.*\/(?<tag>go.*):(?<path>.*);l=(?<line>\d+)$/i | |
); | |
let githubRegex = new RegExp( | |
/github\.com\/(?<repo>.*)\/blob\/(?<tag>v[\w,\-,\_,\d,\.]+)\/(?<path>.*)#L(?<line>\d+)$/i | |
); | |
// iterate over links and add template | |
let pageLinks = Array.from(document.links); | |
let replaced = 0; | |
for (let i = 0; i < pageLinks.length; i++) { | |
const match = | |
googleRegex.exec(pageLinks[i].href) || | |
githubRegex.exec(pageLinks[i].href); | |
if (match) { | |
let { groups } = match; | |
let replacements = { | |
$__tag: groups["tag"], | |
$__path: groups["path"], | |
$__line: groups["line"], | |
$__repo: groups["repo"] || "golang/go", | |
}; | |
replaced++; | |
pageLinks[i].href = sourcegraphLink.replace( | |
/\$__(tag|path|line|repo)/gi, | |
function (matched) { | |
return replacements[matched]; | |
} | |
); | |
} | |
} | |
if (replaced > 0) { | |
console.log(`✅ done! changed ${replaced} links to sourcegraph.com`); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment