Skip to content

Instantly share code, notes, and snippets.

@Genzer
Last active October 26, 2022 09:15
Show Gist options
  • Select an option

  • Save Genzer/46c940c3d7eb9a7bf80e387ad2e4e239 to your computer and use it in GitHub Desktop.

Select an option

Save Genzer/46c940c3d7eb9a7bf80e387ad2e4e239 to your computer and use it in GitHub Desktop.
Unarchive GitHub Repositories using CLI
#!/usr/bin/env bash
set -ueo pipefail
# INTRODUCTION
# ====
#
# This script was created as I wanted to unarchive multiple repositories in our company.
# Using the Web UI would take lots of time and I was lazy as hell. GitHub Rest API also
# did not support it.
# Luckily, I discovered an article [1] giving hint that GitHub GraphQL API did have a
# Mutation for this. Hence this script.
#
# Prerequisites
# ====
# You will need a GitHub Personal Access Token with the correct scopes [2]. Set it to
# the environment variable `GITHUB_TOKEN` before running this script.
#
# Usage
# ====
#
# Invoke this script
# ```bash
# $ bash unarchive_github_repository.sh example some-repo-archived-before
# ```
#
# ----
# [1]: https://www.lotharschulz.info/2020/11/02/repository-archiving-unarchiving-with-github-graphql-api/
# [2]: https://docs.github.com/en/graphql/guides/forming-calls-with-graphql#authenticating-with-graphql
get_repo_id() {
local -r org="$1"
local -r repo_name="$2"
cat <<_PAYLOAD_ \
| curl \
--silent \
--fail \
--show-error \
--url https://api.github.com/graphql \
-K <(echo "\"Authorization: Bearer $GITHUB_TOKEN\"") \
-H 'content-type: application/json' \
--data @- \
| jq -r '.data.repository.id'
{
"query": "query (\$org: String!, \$repo: String!) {repository(owner: \$org, name: \$repo) { id } }",
"variables": {
"org": "$org",
"repo": "$repo_name"
}
}
_PAYLOAD_
}
unarchive() {
local -r repo_id=$1
cat <<_PAYLOAD_ \
| curl \
--silent \
--fail \
--show-error \
--url https://api.github.com/graphql \
-K <(echo "\"Authorization: Bearer $GITHUB_TOKEN\"") \
-H 'content-type: application/json' \
--data @- \
| jq -r
{
"query": "mutation UnArchiveRepository(\$repo: ID!) {\
unarchiveRepository(input:{clientMutationId: \"true\",repositoryId: \$repo}) {\
repository {\
name,\
isArchived,\
}\
}\
}",
"variables": {
"repo": "$repo_id"
}
}
_PAYLOAD_
}
main() {
if (( "$#" == 0 )); then
echo "Missing GitHub Org and Repository."
echo "Usage:"
echo "$ bash unarchive_github_repo.sh ORG REPO"
exit 0
fi
local org="$1"
local repo_name="$2"
local repo_id;
repo_id="$(get_repo_id "$org" "$repo_name")"
unarchive "$repo_id"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment