The GitHub command line utility

It has been some time since GitHub released its command line tool. For someone who spends a ton of their time creating PRs, reviewing them, and merging PRs. If you are someone like me who prefers command line tools over GUI then this is a great tool to interact with GitHub.

Here is the manual https://cli.github.com/manual/ which guides you through the installation process.

In addition to the basic commands to clone, create pull requests, and merge pull requests, what makes this tool really interesting is its ability to call any GitHub API. This makes it very easy to integrate with GitHub and automate tasks. I personally use this tool extensively in my day-to-day work. Here are some of the use cases:

Add a user to an organization

I administer multiple repositories and oftentimes need to add new users to a GitHub Organization. Adding a user through GUI requires multiple clicks and if multiple users need to be added at a time, then this command is very handy. We can have a simple script like shown below:

#! /bin/bash
# to run the script: bash add-to-org.sh <org-name> '<user1,user2,user3 ...>'
# 
export GH_ENTERPRISE_TOKEN=<Your Token>
export GH_HOST_NAME=<your GitHub Hostname> 
for user in $(echo $2 | tr ',' '\n')
do
    gh api --method PUT -H "Accept: application/vnd.github+json" --hostname $GH_HOST_NAME /orgs/$1/memberships/$user -f role='member'
done

Add a repository to an existing GitHub application within your organization

Many times if you have a custom GitHub app in your organization and you need to enable it only for selected repositories then here is a way to do it. This script takes <org-name>, <app-name> and a comma-separated list of repositories.

#! /bin/bash
# to run: install-app.sh <org-name> <app-name> <repo1,repo2,repo3 ...>
export GH_ENTERPRISE_TOKEN=<your github token>
export GH_HOST_NAME=<your GitHub Hostname>
org_name=$1
app_slug=$2
repos=$3
installation_id=$(gh api -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" --hostname $GH_HOST_NAME /orgs/$org_name/installations | jq -r '."installations" | .[] | select(.app_slug == '\"$app_slug\"').id')
for i in $(echo $repos | tr ',' '\n')
do
  repo_id=$(gh api -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" --hostname $GH_HOST_NAME /repos/$org_name/$i | jq -r ".id")
  echo $org_name/$i - $repo_id
  gh api --method PUT -H "Accept: application/vnd.github+json" -H "X-GitHub-Api-Version: 2022-11-28" --hostname $GH_HOST_NAME /user/installations/$installation_id/repositories/$repo_id
done

These are just a few examples of how GitHub CLI can be used for your day-to-day GitHub operations and administration.

Now, in addition to its REST APIs, GitHub has introduced the GitHub GraphQL API, which offers significantly greater power and flexibility. Exploring the capabilities of the GraphQL API warrants its own dedicated post, as it delves into a whole different realm.