Skip to content

Instantly share code, notes, and snippets.

@boneskull
Created January 8, 2019 23:00
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 boneskull/869b17d428d67e93875640a7f22822f1 to your computer and use it in GitHub Desktop.
Save boneskull/869b17d428d67e93875640a7f22822f1 to your computer and use it in GitHub Desktop.
sorts working copies into subdirs by GitHub org name

Given a directory full of working copies, like ~/projects, this script helps sort them into subdirectories based on org name. It inspects Git remote names and URLs to do so.

Currently doesn't handle forks very well, because git doesn't know what a fork is.

NOTE TO SELF: Hub is helpful. Use hub clone and hub fork --remote-name=origin rather than clicking the big green "Fork" button, as this sets up origin/upstream remotes properly.

#!/bin/bash
user=boneskull
get_org() {
export GIT_DIR="${1}/.git"
export GIT_WORK_TREE="${1}"
local upstream="$(git config --get remote.upstream.url)"
local origin="$(git config --get remote.origin.url)"
# prefer upstream
[[ ${upstream} =~ github\.(ibm\.)?com[/:]([^/]+)/ ]] && {
echo "${BASH_REMATCH[2]}"
} || {
[[ ${origin} =~ github\.(ibm\.)?com[/:]([^/]+)/ ]] && {
[[ ${BASH_REMATCH[2]} != ${user} ]] && {
echo "${BASH_REMATCH[2]}"
} || {
# TODO: use GitHub API to determine if this is a fork
echo "${GIT_WORK_TREE} needs manual check" 1>&2
}
} || {
[[ -z ${origin} ]] && {
# no remote
echo "${user}"
} || {
# probably not from GitHub
echo "${GIT_WORK_TREE} needs manual check" 1>&2
}
}
}
export -n GIT_DIR
export -n GIT_WORK_TREE
}
for dir in *
do
[[ -d ${dir} && -d ${dir}/.git ]] && {
dest=$(get_org "$(realpath ${dir})" | tr '[:upper:]' '[:lower:]')
[[ -n ${dest} ]] && {
[[ ${dest} == ${dir} ]] && {
# name collision
mv "${dir}" "${dir}.tmp"
mkdir -p "${dest}"
mv -v "${dir}.tmp" "${dest}/${dir}"
} || {
mkdir -p "${dest}"
mv -v "${dir}" "${dest}"
}
}
}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment