bin/gc

#!/usr/bin/env bash
# bin/gc — git clone helper.
# Clones any URL under ~/code/<host>/<owner>/<repo> for a tidy layout.

set -euo pipefail

usage() {
  cat <<EOF
usage: gc <url> [--bare]

Clones <url> under \$HOME/code/<host>/<owner>/<repo>.
Recognised URL shapes:
  git@github.com:owner/repo(.git)
  https://github.com/owner/repo(.git)
  https://gitlab.com/group/sub/repo(.git)
EOF
}

[[ $# -lt 1 ]] && { usage; exit 2; }

url="$1"; shift || true
extra=("$@")
code_root="${CODE_ROOT:-$HOME/code}"

# Parse the URL: host, path.
case "$url" in
  git@*)
    rest="${url#git@}"
    host="${rest%%:*}"
    path="${rest#*:}"
    ;;
  http*://*)
    rest="${url#*://}"
    host="${rest%%/*}"
    path="${rest#*/}"
    ;;
  *)
    printf 'gc: unrecognised URL: %s\n' "$url" >&2
    exit 2
    ;;
esac

path="${path%.git}"
dest="$code_root/$host/$path"

if [[ -d "$dest/.git" ]]; then
  printf 'gc: already cloned at %s\n' "$dest"
  exit 0
fi

mkdir -p "$(dirname "$dest")"
git clone "${extra[@]}" "$url" "$dest"
printf 'gc: cloned -> %s\n' "$dest"