Saturday, December 3, 2016

How to create gists from the command line


I was a bit astonished that I couldn't find a working example written in bash on the net that would create gists on the github from the command line. Some examples didn't work at all because they were using old github API or because the text escaping weren't properly implemented. The rest didn't have the functionality I needed.
There are of course gist clients available in the repository but as long as I can use standard utilities and bash I try to avoid installing additional software.

To use the script one would need to get a github gist token first.

Provided that a github account exists already, one'd need to login to his account, go to the https://github.com/settings/tokens and generate a new token only for gists (select only 'create gists' checkbox).

Next step is to decide how the gist token should be stored in the system. The script expects to get the token either from the GITOKEN or from GITOKENCMD system variables. If GITOKEN variable is empty the script will eval the GITOKENCMD variable. If both variables aren't set then the GITOKENCMD will be set to:
GITOKENCMD='python3 -c "import keyring; print(keyring.get_password(\"gist\",\"'"$USER"'\"))"'

This python code snippet reads the token from the default system keyring. To make it work the python3-keyring package should be installed first. Additionally proper system keyring backend library should be installed otherwise python will use the plain text backend as a fallback.  If GNOME is used then the gir1.2-gnomekeyring-1.0 library should be installed additionally.

To check what keyring backend is configured execute the following code:
python3 -c 'import keyring; print(keyring.get_keyring())'
And if you see keyring.backends.file.PlaintextKeyring in the output then there's no proper backend configured.

When the keyring backend is properly configured then the gist token could be stored with the following command:
python3 -c 'import keyring; keyring.set_password("gist","'"$USER"'", "MYTOKEN")'

where MYTOKEN is the token string.

 Addionally the following utilities needs to be installed:
  • curl
  • xclip (to put new gist URL into the system clipboard)
  • python3-secretstorage ( could be necessary because of some recent python keyring interface changes)

 

The script has the following command line parametes:
  • -p -- create a public gist (by default a 'secret' gist is created)
  • -d "gist description" -- by default the file name is used (or stdin if content is piped)

 

Usage examples:

xclip -o | gistit -d "private gist of the system clipboard content"
gistit -p -d "gistit script" bin/gistit

 

And the first gist created with the script was the gist of itself of course:

No comments: