Skip to content

Instantly share code, notes, and snippets.

@Frederick888
Created December 31, 2021 13:31
Show Gist options
  • Save Frederick888/73152ebda9d0a0d081366b7444a89720 to your computer and use it in GitHub Desktop.
Save Frederick888/73152ebda9d0a0d081366b7444a89720 to your computer and use it in GitHub Desktop.
Import PGP keys in a Git repository from GitHub
#!/usr/bin/env bash
OWNER="$1"
REPO="$2"
declare -A PROCESSED
function import_github_pgp() {
local github_login="$1"
printf 'Importing PGP key of GitHub user %s\n' "$github_login"
curl "https://github.com/$github_login.gpg" | gpg --import
}
function github_login_from_commit() {
local commit_hash="$1"
local response
if ! response="$(gh api "repos/$OWNER/$REPO/commits/$commit_hash")"; then
printf 'Failed to retrieve info of commit %s\n' "$commit_hash"
return 1
fi
local verified
verified="$(jq -r .commit.verification.verified <<<"$response")"
if [[ "$verified" != "true" ]]; then
printf 'Commit %s is not verified\n' "$commit_hash"
return 1
fi
local github_login
github_login="$(jq -r .author.login <<<"$response")"
printf '%s' "$github_login"
}
if [[ -z "$OWNER" ]] || [[ -z "$REPO" ]]; then
owner_repo="$(git remote get-url --no-push origin | sed -n 's/.*[:\/]\([-_a-zA-Z0-9]\+\)\/\([-_a-zA-Z0-9]\+\)\(\.git\)\?$/\1 \2/p')"
if [[ -z "$owner_repo" ]]; then
printf 'Please provide owner and repository name\n'
exit 1
fi
OWNER="$(cut -d ' ' -f 1 <<<"$owner_repo")"
REPO="$(cut -d ' ' -f 2 <<<"$owner_repo")"
printf 'Detected repository https://github.com/%s/%s, continue? [y/n] ' "$OWNER" "$REPO"
read -n1 -r
printf '\n'
if [[ "$REPLY" != 'y' ]]; then
exit 0
fi
fi
while read -r commit_hash; do
printf 'Processing commit %s\n' "$commit_hash"
email="$(git show -s --format='%ae' "$commit_hash")"
primary_key="$(git show -s --format='%GP' "$commit_hash")"
if [[ -n "${PROCESSED[$primary_key]}" ]]; then
printf 'Skipping commit %s since key %s for author email %s has been processed\n' "$commit_hash" "$primary_key" "$email"
continue
fi
PROCESSED["$primary_key"]=1
if github_login="$(github_login_from_commit "$commit_hash")" && [[ -n "$github_login" ]]; then
import_github_pgp "$github_login"
fi
done < <(git log --format='%H %G?' | sed -u -n 's/ E$//p')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment