Skip to content

Instantly share code, notes, and snippets.

@jorgelbg
Last active May 17, 2023 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorgelbg/8a5d12f39009207becec4da452b553c7 to your computer and use it in GitHub Desktop.
Save jorgelbg/8a5d12f39009207becec4da452b553c7 to your computer and use it in GitHub Desktop.
UserScript for rewriting pkg.go.dev links to always use sourcegraph.com
// ==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 <github@jorgelbg.me>
// @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