ghtp 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/env bash
  2. #
  3. # ghtp (GitHub Transport Protocol)
  4. #
  5. # Set all remotes in the current repo to HTTPS or SSH connection.
  6. # Useful when switching environments, using public wifi, etc.
  7. #
  8. # Optionally, specify a particular remote to change.
  9. #
  10. GH_SSH="git@github\.com:"
  11. GH_HTTPS="https:\/\/github\.com\/"
  12. case "$1" in
  13. -[Hh]) TYPE=HTTPS ; MATCH="git@" ; REPLACE="$GH_SSH/$GH_HTTPS" ;;
  14. -[Ss]) TYPE=SSH ; MATCH="https:" ; REPLACE="$GH_HTTPS/$GH_SSH" ;;
  15. *)
  16. echo "Usage: `basename $0` -h | -s" 1>&2
  17. echo -e " \e[0;92m-h\e[0m to switch to HTTPS" 1>&2
  18. echo -e " \e[0;92m-s\e[0m to switch to SSH" 1>&2
  19. exit 1
  20. ;;
  21. esac
  22. AWK=$(which gawk || which awk)
  23. # Match all or specified remotes of the other type
  24. REGEX="\t$MATCH" ; [[ $# > 1 ]] && REGEX="^$2$REGEX"
  25. REMOTES=$(git remote -v | egrep "$REGEX" | "$AWK" '{print $1 " " $2}' | sort -u | sed "s/$REPLACE/")
  26. [[ -z $REMOTES ]] && { echo "Nothing to do." ; exit ; }
  27. # Update a remote for each results pair
  28. echo "$REMOTES" | xargs -n2 git remote set-url
  29. echo -n "Remotes set to $TYPE: "
  30. echo "$REMOTES" | "$AWK" '{printf "%s ", $1}'
  31. echo