Skip to content

Instantly share code, notes, and snippets.

@wf9a5m75
Last active June 28, 2018 01:23
Show Gist options
  • Save wf9a5m75/56cdb6a297d38aaa6440 to your computer and use it in GitHub Desktop.
Save wf9a5m75/56cdb6a297d38aaa6440 to your computer and use it in GitHub Desktop.
Download a file from your github repository directly (without git clone). You need to get your personal access key at https://github.com/settings/tokens
#!/usr/bin/env bash
export GITHUB_ACCESS_TOKEN=""
export GITHUB_USERNAME=""
export REPO_OWNER=""
BRANCH=""
REPO=""
FILE_PATH=""
. ~/.profile
if [ $# -eq 1 ] && [[ "$1" =~ ^https:\/\/github.com\/([a-zA-Z0-9_\-]+)/([a-zA-Z0-9_\-]+)\/blob\/([^\/]+)\/(.+) ]]; then
REPO_OWNER=${BASH_REMATCH[1]}
REPO=${BASH_REMATCH[2]}
BRANCH=${BASH_REMATCH[3]}
FILE_PATH=${BASH_REMATCH[4]}
else
if [ $# -ne 2 ]; then
SCRIPT=$(basename $0)
echo "Usage"
echo " $SCRIPT <repository name> <file path>"
echo " or "
echo " $SCRIPT https://github.com/<repository owner>/<repository name>/blob/<branch>/<filepath>"
exit
fi
BRANCH="master"
REPO="$1"
FILE_PATH="$2"
fi
if [ -z "${GITHUB_ACCESS_TOKEN}" ]; then
echo "You need to define your GITHUB_ACCESS_TOKEN in ~/.profile"
exit 1
fi
if [ -z "${GITHUB_USERNAME}" ]; then
echo "You need to define your GITHUB_USERNAME in ~/.profile"
exit 1
fi
if [ -z "${REPO_OWNER}" ]; then
echo "You need to define your REPO_OWNER in ~/.profile"
exit 1
fi
CURL=$(which curl)
if [ -z "${CURL}" ]; then
echo "curl command is required."
exit 1
fi
JQ=$(which jq)
if [ -z "${JQ}" ]; then
echo "jq command is required."
exit 1
fi
function CURL_GITHUB () {
COMMAND="$1"
echo $(curl \
-s -L -G \
--user "${GITHUB_USERNAME}:${GITHUB_ACCESS_TOKEN}" \
-H "Accept: application/vnd.github.chitauri-preview+sha" \
"https://api.github.com/repos/${REPO_OWNER}/${REPO}${COMMAND}")
}
#-----------------------------------------
# Get the latest sha of master tree
#-----------------------------------------
TREE_SHA=$(CURL_GITHUB "/commits/${BRANCH}")
if [ -z "${TREE_SHA}" ]; then
echo "Cannot get the tree sha. Please confirm your credentials."
exit 1;
fi
#-----------------------------------------
# Get the tree of the parent directory
#-----------------------------------------
PARENT_DIR=$(dirname ${FILE_PATH})
if [[ "${PARENT_DIR}" == "." ]]; then
PARENT_DIR="/"
fi
FILENAME=$(basename $FILE_PATH)
FILES=$(CURL_GITHUB "/contents/${PARENT_DIR}")
GIT_BLOB_URL=$(echo $FILES | jq -r ".[] | select(.name==\"${FILENAME}\") | .git_url")
curl -s -L -G -r 5 --user "${GITHUB_USERNAME}:${GITHUB_ACCESS_TOKEN}" ${GIT_BLOB_URL} | jq -r ".content" | base64 --decode - > ${FILENAME}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment