#!/bin/sh set -e # set -x gitRoot='' # 获取git项目目录 getGitRoot(){ root=$(pwd) if [ -d "./.git" ]; then echo "$root" else [ "$root" != "/" ] && cd ../ && getGitRoot fi cd "$root" } # 拉取远程分支 fetchAll(){ git fetch --all } # 获取当前分支名 getCurrentBranch(){ branch=$(git rev-parse --abbrev-ref HEAD) echo "$branch"; } # 重制分支 resetHard(){ currentBranch=$(getCurrentBranch) git reset --hard "origin/$currentBranch"; if [ -n "$1" ] && [ "$currentBranch" != "$1" ]; then git checkout "$1"; if [ $? -eq 1 ]; then return; fi fi } # 重制到最新的分支版本 resetToLast(){ fetchAll; deleteChangeFiles; resetHard "$1"; git pull git diff; git status; } # 获取未添加到git分支的文件 getChangeFiles(){ git status --porcelain 2>/dev/null | awk '{print $2}' } # 删除未添加到git分支的所有文件 deleteChangeFiles(){ getChangeFiles | xargs -n1 rm -rf } help() { printf "resetToLast [branchName]\n" printf "getChangeFiles\n" printf "cleanFiles\n" printf "getGitRoot\n" } main(){ # 切换至git主目录 gitRoot=$(getGitRoot) if [ -z "$gitRoot" ]; then printf "Not a git repository (or any of the parent directories): .git\n" exit 1 fi cd "$gitRoot" || exit 1 case $1 in 'resetToLast') resetToLast "$2" ;; 'getChangeFiles') getChangeFiles ;; 'cleanFiles') deleteChangeFiles ;; 'getGitRoot') echo "$gitRoot" ;; '-h' | '--help') help ;; *) printf 'no options!!\n' help ;; esac } main "$@";