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:

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:
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:

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)

 

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:


 

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

No comments: