Created
January 13, 2020 09:51
-
-
Save PurpleMyst/37e0e19a594925868dc41f053d30d662 to your computer and use it in GitHub Desktop.
Create gists from the command line
This file contains 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
#!/usr/bin/env zsh | |
setopt ERR_EXIT NO_UNSET PIPE_FAIL | |
unsetopt FUNCTION_ARGZERO | |
if [[ -z ${GIST_API_TOKEN:-} ]]; then | |
if [[ -f ${XDG_CONFIG_HOME:-$HOME/.config}/gist-api-token.txt ]]; then | |
GIST_API_TOKEN=$(cat ${XDG_CONFIG_HOME:-$HOME/.config}/gist-api-token.txt) | |
else | |
printf 'No GIST API token provided!\n' | |
exit 1 | |
fi | |
fi | |
usage() { | |
printf 'USAGE: %s create [--public | --secret] [--description DESCRIPTION] FILENAME\n' $0 | |
exit 1 | |
} | |
if [[ ${1:-} == create ]]; then | |
shift | |
declare -a filenames | |
while [[ $# -gt 0 ]]; do | |
case $1 in | |
--public) | |
if [[ -z ${public:-} ]]; then | |
public=true | |
shift | |
else | |
usage | |
fi | |
;; | |
--secret) | |
if [[ -z ${public:-} ]]; then | |
public=false | |
shift | |
else | |
usage | |
fi | |
;; | |
--description) | |
if [[ -z ${description:-} && $# -ge 2 ]]; then | |
description=$2 | |
shift 2 | |
else | |
usage | |
fi | |
;; | |
-*) | |
usage | |
;; | |
*) | |
filenames+=$1 | |
shift | |
;; | |
esac | |
done | |
if [[ ${#filenames} -eq 0 ]] usage | |
# Create the files item for a given file | |
file_item() { | |
jq \ | |
--arg filename $1 \ | |
--rawfile content $1 \ | |
--null-input \ | |
'{ ($filename): { content: $content } }' | |
} | |
# We store the request body into a variable because wget must know its size to | |
# send as the Content-Length header. | |
# To create the files value, create the file item for each individual file, then | |
# use the `add` jq function to merge them into a single object | |
body=$( | |
for f (${filenames[*]}) { file_item $f } \ | |
| jq \ | |
--arg description "${description:-}" \ | |
--argjson public ${public:-true} \ | |
--slurp \ | |
'{ files: add, description: $description, public: $public }' | |
) | |
wget 'https://api.github.com/gists' \ | |
--post-data $body \ | |
--header 'Content-Type: application/json' \ | |
--header 'Accept: application/json' \ | |
--header "Authorization: token $GIST_API_TOKEN" \ | |
--output-document=- \ | |
--user-agent 'create-gist.sh/1.0.0' \ | |
--quiet \ | |
| jq -r '.html_url' | |
else | |
usage | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment