Skip to content

Instantly share code, notes, and snippets.

@phwt
Last active March 13, 2024 01:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phwt/5023660b60bde483c57784e979e40517 to your computer and use it in GitHub Desktop.
Save phwt/5023660b60bde483c57784e979e40517 to your computer and use it in GitHub Desktop.
Rename local Git directory to match the current remote name in GitHub
export GH_PAT="ghp_xxxxxxxxxxxxxxxxxxxxxxxx"
for dir in */; do
cd "$dir" || exit
if [ -d .git ]; then
cleaned_dir=$(echo $dir | sed 's:/*$::') # Remove trailing slash
if git remote get-url origin &>/dev/null; then
remote_url=$(git remote get-url origin)
repo_ref=$(basename "$(dirname "$remote_url")")/$(basename "$remote_url" | sed 's:.git*$::')
new_repo_ref=$(curl -L -s \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GH_PAT" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/$repo_ref | jq -r .name)
new_repo_name=$(basename $new_repo_ref)
if [[ $new_repo_name == "null" ]]; then
echo "Unable to retrieve repository name: \`$cleaned_dir\`"
else
if [[ $cleaned_dir == $new_repo_name ]]; then
echo "Using the same name as in remote: \`$cleaned_dir\`"
else
mv ../$cleaned_dir ../$new_repo_name
echo "Renamed \`$cleaned_dir\` to \`$new_repo_name\`"
fi
fi
else
echo "Remote \`origin\` does not exist for \`$cleaned_dir\`"
fi
else
echo "Not a Git directory: \`$cleaned_dir\`"
fi
cd ..
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment