#default_exp cli
#export
from fastcore.utils import *
import ghapi.core as gh,inspect
from ghapi.core import *
from collections import defaultdict
Access to the GitHub API from the command line
You can use GhApi
via the command line, and can access nearly everything in the GitHub API.
There are three commands provided. For most people, ghapi
will be the easiest to use. All three commands take the following parameters:
--help
: list all parameters to this command and endpoint--headers
: A list of extra headers to pass, JSON-encoded--token
: A GitHub authentation token--debug
: Print requests before sending themIf you have an environment variable GITHUB_TOKEN
defined, then it will be used for the token if --token
is not passed. If neither is provided, then the commands will not be able to acces any authentication functionality.
We'll now look at each of the three commands in turn.
ghapi
command¶To get started with the ghapi
command, first find the name of the operation you wish to perform. If you've used the Python API, then you already know the operation names - they're whatever you type in Python after "api.
". To find the name of the operation you need, search the full API reference which contains information about every endpoint in the entire GitHub API. For instance, if you want to work with GitHub Issues, then searching for "issues" on the full reference page will take you to this section.
The first operation listed there is issues.list, shown with a link to the official GitHub documentation, and a list of parameters that the command accepts. You'll see the official docs list some parameters, such as "accept
", which aren't listed in the GhApi reference - that's because GhApi automatically set some parameters for you.
You'll also see that the parameter list on the official docs includes a column marked "in", which can be "header", "query", "path", or "body". The ghapi
command handles that distinction for you, so you can ignore it for now.
#export
def _parse_args(a):
"Extract positional and keyword arguments from `a`=`sys.argv`"
pos,kw = [],{}
i=1
while i<len(a):
x = a[i]
if x[:2]=='--':
k = x[2:]
if k in ('help','debug'): y = 1
else:
i += 1
y = a[i]
kw[k] = y
else: pos.append(a[i])
i += 1
return a[0],pos,kw
def _api():
"Result of `_parse_args` along with `GhApi`"
cmd,pos,kw = _parse_args(sys.argv)
token = kw.pop('token',None) or os.getenv('GITHUB_TOKEN')
api = GhApi(token=token, debug=print_summary if kw.pop('debug',None) else None)
return cmd,api,pos,kw
def _call_api(f):
"Call `f`, passing in args parsed from `sys.argv`"
cmd,api,pos,kw = _api()
if not pos: return print(f"Usage: `{cmd}` operation <params>")
call = f(pos, api)
return call if kw.get('help', None) else call(*pos, **kw)
#export
def _ghapi(arg, api):
for part in arg.pop(0).split('.'): api = getattr(api,part)
return api
#hide
#export
def ghapi():
"Python backend for the `ghapi` command, which calls an endpoint by operation name"
res = _call_api(_ghapi)
if isinstance(res, (gh._GhObj,dict)): print(res)
elif res: print(inspect.signature(res))
To use ghapi
, pass the method name (exactly the same as you'd use in the Python API) as the first parameter, followed by any positional parameters required, and then keyword arguments with "--
" before each parameter name.
For instance, git.get_ref takes three parameters: owner
, repo
, and ref
. If we wish to pass the first two as positional parameters, and the last as a named argument, then we'd call:
! ghapi git.get_ref fastai ghapi-test --ref heads/master
- ref: refs/heads/master - node_id: MDM6UmVmMzE1NzEyNTg4OnJlZnMvaGVhZHMvbWFzdGVy - url: https://api.github.com/repos/fastai/ghapi-test/git/refs/heads/master - object: - sha: f086d17cc9ec8e99f466c613cab44f98abad1db6 - type: commit - url: https://api.github.com/repos/fastai/ghapi-test/git/commits/f086d17cc9ec8e99f466c613cab44f98abad1db6
(NB: The "!
" before the examples such as the one above is only needed when calling the commands from Jupyer Notebook. In your terminal, do not include the "!
" prefix.)
If you pass just --help
after the operation name, you'll see a full list of all parameters accepted, and a link to the official GitHub documentation.
! ghapi git.get_ref --help
git.get_ref(owner, repo, ref) https://docs.github.com/rest/reference/git#get-a-reference
Helper methods are also supported, e.g:
! ghapi create_release --help
(tag_name, branch='master', name=None, body='', draft=False, prerelease=False, files=None)
ghpath
command¶If you find the endpoint you want in the GitHub docs, rather than the GhApi reference, you'll see a path
and a verb
instead of an operation name. For example, here's the GitHub documentation for git.getref. The white text on blue background section shows that the verb required is "GET
". Next to that is the path, which is listed as "/repos/{owner}/{repo}/git/ref/{ref}
".
To call an endpoint when you have this information from the GitHub docs, use the ghpath
command. The arguments are exactly the same as ghapi
, except that instead of an operation name, you provide the path (which you can paste directly from the GitHub docs) and verb.
#export
def _ghpath(arg, api): return api[arg.pop(0),arg.pop(0)]
#hide
#export
def ghpath():
"Python backend for the `ghpath` command, which calls an endpoint by path"
print(_call_api(_ghpath) or '')
Just like with ghapi
, ghpath
handles header, query, path and body parameters for you automatically.
For instance, the previous git.get_ref
command using ghpath
is:
! ghpath '/repos/{owner}/{repo}/git/ref/{ref}' get fastai ghapi-test --ref heads/master
- ref: refs/heads/master - node_id: MDM6UmVmMzE1NzEyNTg4OnJlZnMvaGVhZHMvbWFzdGVy - url: https://api.github.com/repos/fastai/ghapi-test/git/refs/heads/master - object: - sha: f086d17cc9ec8e99f466c613cab44f98abad1db6 - type: commit - url: https://api.github.com/repos/fastai/ghapi-test/git/commits/f086d17cc9ec8e99f466c613cab44f98abad1db6
ghraw
command¶#hide
#export
def ghraw():
"Python backend for the `ghraw` command, which calls a fully-specified endpoint"
cmd,api,pos,kw = _api()
if not pos: return print(f"Usage: `{cmd}` operation <params>")
print(api(*pos, **kw))
Sometimes, you just want to call an exact path directly, handling the path and query parameters yourself. The ghraw
command provides that functionality. Like with ghpath
, you pass the path and verb as the first two arguments, but now you have to fill in all the path parameters yourself, plus construct the query string yourself (if one is required). If you need to pass body parameters, use the --data
parameter, which requires that you encode the request body appropriately (which is JSON-encoded for most GitHub endpoints).
For instance, the git.git_ref
example show in the previous two sections does not have any header, body, or query parameters, so we need only insert the path parameters, which results in this call:
! ghraw /repos/fastai/ghapi-test/git/ref/heads/master get
- ref: refs/heads/master - node_id: MDM6UmVmMzE1NzEyNTg4OnJlZnMvaGVhZHMvbWFzdGVy - url: https://api.github.com/repos/fastai/ghapi-test/git/refs/heads/master - object: - sha: f086d17cc9ec8e99f466c613cab44f98abad1db6 - type: commit - url: https://api.github.com/repos/fastai/ghapi-test/git/commits/f086d17cc9ec8e99f466c613cab44f98abad1db6
Shell completions are provided for ghapi
behind the scenes by the completion-ghapi
command (which is implemented with the completion_ghapi
function). You probably won't need to call this yourself - it will be called for you as part by your shell.
#hide
#export
_TAB_COMPLETION="""
_do_ghapi_completions()
{
COMP="$(completion-ghapi "${COMP_WORDS[1]}")"
COMPREPLY=($COMP)
}
complete -F _do_ghapi_completions ghapi
"""
#hide
#export
def completion_ghapi():
"Python backend for `completion-ghapi` command"
if len(sys.argv) == 2 and sys.argv[1] == '--install':
print(_TAB_COMPLETION)
return
*parts,final = (sys.argv[1] if len(sys.argv)>1 else '').split('.')
call = GhApi()
for part in parts: call = getattr(call,part)
if hasattr(call,final): res = [final]
else: res = [o for o in dir(call) if o.startswith(final) and not o.startswith('_')]
pre = '.'.join(parts+[final])
print(' '.join(pre + remove_prefix(o, final) for o in res))
! completion-ghapi git
git
! completion-ghapi gi
gists git gitignore
! completion-ghapi git.
git.create_blob git.create_commit git.create_ref git.create_tag git.create_tree git.delete_ref git.get_blob git.get_commit git.get_ref git.get_tag git.get_tree git.list_matching_refs git.name git.update_ref git.verbs
! completion-ghapi git.g
git.get_blob git.get_commit git.get_ref git.get_tag git.get_tree
You can enable tab completion for ghapi
by placing the following command at the end of your ~/.bashrc
or ~/.zshrc
file:
eval "$(completion-ghapi --install)"
#hide
! completion-ghapi --install
_do_ghapi_completions() { COMP="$(completion-ghapi "${COMP_WORDS[1]}")" COMPREPLY=($COMP) } complete -F _do_ghapi_completions ghapi
#hide
from nbdev.export import notebook2script
notebook2script()
Converted 00_core.ipynb. Converted 01_cli.ipynb. Converted 50_fullapi.ipynb. Converted 90_build_lib.ipynb. Converted Enable Pages.ipynb. Converted Untitled.ipynb. Converted index.ipynb.