Skip to content

Instantly share code, notes, and snippets.

@augustohp
Last active April 11, 2023 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save augustohp/57e6bc6ceec2bb01c2ff3cf3b15db4f2 to your computer and use it in GitHub Desktop.
Save augustohp/57e6bc6ceec2bb01c2ff3cf3b15db4f2 to your computer and use it in GitHub Desktop.
Script (bash) to clone all repositories from a user or organization in GitHub.
#!/usr/bin/env bash
#
# Clones all repositories in an organization using `gh` CLI.
#
# Author: Augusto Pascutti <augusto.hp+oss@gmail.com>
# License: MIT
# vim: ft=sh noet ts=2 sw=2:
APP_NAME="$(basename $0)"
APP_VERSION="1.0.0"
if [ -n "$DEBUG" ]
then
set -x
fi
# Sanity checks ---------------------------------------------------------------
for dependency in gh awk sed
do
command -v "$dependency" > /dev/null 2>&1 \
|| { echo "Error: Missing $dependency." >&2; exit 42; }
done
# Program ---------------------------------------------------------------------
# Usage: display_help
display_help()
{
cat <<-EOT
Usage: $APP_NAME <owner>
Clones all source repositories from "owner" (on GitHub) in the
current directory.
EOT
}
# Example: gh_repos augustohp
# Usage: gh_repos <owner>
gh_repos()
{
owner="$1"
test -z "$owner" && { echo "Error: An owner must be specified." >&2; exit 10; }
gh repo list --limit 200 --source --no-archived "$owner" | awk '{print $1 }'
}
# Example: gh_clone augustohp/warwick
# Usage: gh_clone <owner/repo>
gh_clone()
{
repo="$1"
dir="$(echo "$repo" | awk -F/ '{print $2}')"
test -z "$repo" && { echo "Error: A repo (owner/repo-name) must be specified." >&2; exit 11; }
if [ -d "$dir" ]
then
echo "Warning: '$repo' already cloned." >&2
else
echo "Cloning '$repo'..."
gh repo clone "$repo" 2>&1 | sed 's/^/ /' | grep -v "Cloning into"
fi
}
# Usage: main <owner>
main()
{
owner="$1"
test -z "$owner" && { echo "Error: An owner must be specified." >&2; exit 10; }
for repository in $(gh_repos "$owner")
do
gh_clone "$repository"
done
}
while :;
do
case "$1" in
-h | --help)
display_help
exit 1
;;
-v | --version)
echo "$APP_NAME $APP_VERSION"
exit 2
;;
-?*)
echo "Error: Unknown option '$1'." >&2
exit 3
;;
*)
break
;;
esac
done
main "$1"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment