Skip to content

Instantly share code, notes, and snippets.

@westc
Last active August 23, 2019 18:13
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 westc/afac9258389fdfd2fdaf134ffaa0e923 to your computer and use it in GitHub Desktop.
Save westc/afac9258389fdfd2fdaf134ffaa0e923 to your computer and use it in GitHub Desktop.
Get the contents of a file or directory in Git using this function on any web page.
/**
* Gets the GitHub contents of a file or directory.
* @param {string} user
* The GitHub user name.
* @param {string} repo
* The name of the repo. If you want to also specify the branch then you can
* append a colon to the repo name and then specify the branch name in this
* same field.
* @param {string} path
* The path to the file or directory whose contents should be retrieved.
* @param {function(*,*,Object)} callback
* The callback function that will be called with the contents of the GitHub
* file or directory. The arguments passed to this callback will be the (1)
* contents found, (2) the data object, and (3) the meta object. The first
* argument will be the base64 decoded content if the encoding used by GitHub
* was base64. Otherwise the first argument will be the data specified by
* GitHub. If the specified path is for a directory the first argument will
* be an array of objects representing the contents of the directory.
*/
function getGitContents(user, repo, path, callback) {
let tmpName = ('_' + Math.random() + Math.random()).replace(/\./g, '');
window[tmpName] = function (result) {
delete window[tmpName];
let { data, meta } = result;
let contents = Array.isArray(data)
? data
: data.encoding === 'base64'
? atob(data.content)
: data;
callback(contents, data, meta);
};
let branch = 'master';
repo = repo.replace(/:([^:]+)/, function(match, branchName) {
branch = branchName;
});
let url = `https://api.github.com/repos/${user}/${repo}/contents/`
+ path.replace(/[^\/]+/, encodeURIComponent)
+ `?callback=${tmpName}&ref=${encodeURIComponent(branch)}`;
let script = document.createElement('script');
script.src = url;
(document.head || document.body).appendChild(script);
}
// Get the contents of the README.md file from westc's repo called grafana-vuehtml-panel on the master branch:
getGitContents('westc', 'grafana-vuehtml-panel:master', 'README.md', function(contents, data, meta) {
console.log(contents);
});
// Get the contents of the README.md file from westc's repo called grafana-vuehtml-panel:
getGitContents('westc', 'grafana-vuehtml-panel', 'README.md', function(contents, data, meta) {
console.log(contents);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment