Last active
April 25, 2018 04:51
-
-
Save martianyi/15204d056da520639574cc22f7fd3f90 to your computer and use it in GitHub Desktop.
bookmarklet to view file in rawgit.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
javascript: (function() { | |
let devDomain = 'rawgit.com'; | |
const GITHUB_API_URL = 'https://api.github.com'; | |
const REGEX_GIST_URL = /^https?:\/\/gist\.github\.com\/.+?\/([0-9a-f]+)(?:\/([0-9a-f]+))?/i; | |
const REGEX_RAW_GIST_URL = /^https?:\/\/gist\.githubusercontent\.com\/(.+?\/[0-9a-f]+\/raw\/(?:[0-9a-f]+\/)?.+\..+)$/i; | |
const REGEX_RAW_REPO_URL = /^https?:\/\/raw\.github(?:usercontent)?\.com\/(.+?)\/(.+?)\/(.+?)\/(.+)/i; | |
const REGEX_REPO_URL = /^https?:\/\/github\.com\/(.+?)\/(.+?)\/(?!releases\/)(?:(?:blob|raw)\/)?(.+?)\/(.+)/i; | |
formatUrl(); | |
function formatRawGistUrl(url) { | |
location = url.replace(REGEX_RAW_GIST_URL, 'https://' + devDomain + '/$1'); | |
} | |
function formatRawRepoUrl(url) { | |
location = url.replace(REGEX_RAW_REPO_URL, 'https://' + devDomain + '/$1/$2/$3/$4'); | |
} | |
function formatRepoUrl(url) { | |
location = url.replace(REGEX_REPO_URL, 'https://' + devDomain + '/$1/$2/$3/$4'); | |
} | |
function formatUrl() { | |
let url = location.href; | |
if (REGEX_RAW_REPO_URL.test(url)) { | |
formatRawRepoUrl(url); | |
} else if (REGEX_RAW_GIST_URL.test(url)) { | |
formatRawGistUrl(url); | |
} else if (REGEX_REPO_URL.test(url)) { | |
formatRepoUrl(url); | |
} else if (REGEX_GIST_URL.test(url)) { | |
requestGistUrl(url); | |
} | |
} | |
function requestGistUrl(url) { | |
let matches = url.match(REGEX_GIST_URL); | |
let apiUrl = GITHUB_API_URL + '/gists/' + matches[1] + (matches[2] ? '/' + matches[2] : ''); | |
return fetch(apiUrl) | |
.then(res => res.json()) | |
.then(data => { | |
let files = data && data.files; | |
let filenames = files && Object.keys(data.files); | |
if (!filenames || !filenames.length) { | |
return null; | |
} | |
let rawUrl = files[filenames[0]] && files[filenames[0]].raw_url; | |
if (rawUrl) { | |
formatRawGistUrl(rawUrl); | |
} | |
}); | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment