Last active
January 24, 2018 22:28
-
-
Save geirha/15103ebee61f2b129f2897be2397da2a to your computer and use it in GitHub Desktop.
Function to print the contents of a gist in a terminal
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
# Usage: gist url-or-hash or gist [-p] [file...] | |
# | |
# Given a url or hash, print a dump of the gist. Otherwise, create a new | |
# gist of the given file arguments, or stdin if no files are given. | |
# -p forces the arguments to be treated as files to be posted. | |
# | |
# Examples: | |
# | |
# - dump a gist in the terminal: | |
# gist https://gist.github.com/geirha/15103ebee61f2b129f2897be2397da2a | |
# | |
# - create a new gist with two files | |
# gist file1.txt file2.txt | |
gist() { | |
local hash re='^(https?://[^/]*/[^/]*/)?([[:xdigit:]]{32})' post | |
case $1 in -p) post=1; shift ;; esac | |
[[ $1 = -- ]] && shift | |
if (( !post && $# == 1 )) && [[ $1 =~ $re ]]; then | |
hash=${BASH_REMATCH[2]} | |
curl -sSf "https://api.github.com/gists/$hash" | | |
jq -r '.files | values[] | (.content|contains("\r")) as $cr | ( | |
"==> \(.filename) \(if ($cr) then "(Contains CRs) " else "" end)<==", | |
.content | |
)' | |
(( PIPESTATUS[0] == 0 )) || return | |
curl -sSf "https://api.github.com/gists/$hash/comments" | | |
jq -r 'if (length > 0) then | |
"=== Comments ===", | |
(.[]|("\(.user.login) \(.updated_at)","\t\(.body|gsub("\n";"\n\t"))")) | |
else | |
"" | |
end' | |
else | |
{ | |
local name | |
while (( $# > 1 )); do | |
name=${1##*/} | |
jq --arg name "$name" -sR '{($name):{"content":.}}' "$1" | |
shift | |
done | |
name=${1-stdin} name=${name##*/} | |
jq --arg name "$name" -sR '{($name):{"content":.}}' "$@" | |
} | | |
jq -s 'add|{"files":.}' | | |
curl -sSf -d @- https://api.github.com/gists | | |
jq -r .html_url | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment