Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 1e73e565b0
Fetching contributors…

Cannot retrieve contributors at this time

executable file 120 lines (103 sloc) 2.158 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
#!/bin/bash

CURRENT=$(git symbolic-ref -q HEAD || git rev-parse HEAD)
CURRENT=${CURRENT#refs/heads/}

# default settings
explain=false
verbose=true
run=true

# colors
RED="\033[0;31m"
YELLOW="\033[1;33m"
GREEN="\033[0;32m"
NO_COLOR="\033[0m"

die() {
  echo -e "${RED}${@}${NO_COLOR}"
  exit 1
}

warn() {
  echo -e "${YELLOW}${@}${NO_COLOR}"
}

good() {
  echo -e "${GREEN}${@}${NO_COLOR}"
}

printUsage() {
  echo "usage: git-open BRANCH"
  echo "Creates a new branch named BRANCH by forking master or, if"
  echo "a branch by that name exists, it checks that branch out."
  echo ""
  echo "Given these branches:"
  echo ""
  echo " sh-$ git branch"
  echo " * master"
  echo " performance"
  echo ""
  echo "Creating a new branch"
  echo ""
  echo " sh-$ git open test"
  echo " + git checkout -b test"
  echo " Switched to a new branch \"test\""
  echo ""
  echo "Switching to an existing branch"
  echo ""
  echo " sh-$ git open performance"
  echo " + git checkout performance"
  echo " Switched to branch \"performance\""
}

for arg in "$@"; do
  case $arg in
    -e | --explain | --dry-run)
      explain=true
verbose=true
run=false
      ;;
    -v | --verbose)
      verbose=true
      ;;
    -q | --quiet)
      verbose=false
      ;;
    -h | --help)
      printUsage
      exit 0
      ;;
    -*)
      warn "${YELLOW}$0: unrecognized parameter '$arg'${NO_COLOR}"
      exit 1
      ;;
    *)
      TARGET=$arg
      ;;
  esac
done

GIT=`which git`

git() {
  if [ "$verbose" = true ]; then
    echo -e "+ ${GREEN}git $@${NO_COLOR}"
  fi

  if [ "$run" = true ]; then
    eval "$GIT $@"
  fi
}

if [ "$CURRENT" = "$TARGET" ]; then
  echo "Already on branch $TARGET"
  exit
fi

if [ "$CURRENT" != "master" ]; then
  git checkout master
fi

if [ "$TARGET" = "master" ]; then
  exit
fi

if [ -z "$TARGET" ]; then
  warn "Please provide a branch name"
  printUsage
  exit 1
fi

$GIT rev-parse "$TARGET" 2>/dev/null >/dev/null &&
  git checkout "$TARGET" ||
  git checkout -b $TARGET

if [[ $? = 0 && $run = true ]]; then
  good "Now working on $TARGET"
elif [ $run = true ]; then
  die "Could not start working on $TARGET"
fi
Something went wrong with that request. Please try again.