Git best practices

Git 基本操作

创建Git仓库

1
git init

查看代码情况

1
2
git status
git diff {filepath}

提交代码

1
2
3
4
git clone {clone.git}
git add -A
git commit -m "message"
git push orgin master

保存/恢复临时修改文件

1
2
git stash
git checkout stash@{0} -- {filepath}

读取文件历史版本

1
git checkout {commithash} -- {filepath}

创建标签

1
2
3
git tag -a v1.0  # tag most recent commit
git tag -a v0.9 85fc7e7 # tag on a specific commit
git tag # view tags

Pull/Fork工作流

  1. fork from the github
  2. clone to local and commit changes
    1
    2
    3
    4
    5
    6
    git clone {clone.git}
    git checkout -b feature
    # make changes to this branch
    git add -p
    git commit -m "feature message"
    git push origin feature
  3. rebase commits after remote master
    1
    2
    3
    4
    5
    6
    7
    git remote add upstream {remote.git}
    git pull upstream master
    # no changes on master, then automatically git history is updated
    git checkout feature
    git pull --rebase origin master
    # apply changes from origin master to feature newly commits
    git push origin feature --force
  4. raise pull request for code review

提交历史管理

缩减冗余commit log

  • 通过rebase修改commit history
1
2
3
# rewrite last 10 commit logs
git rebase -i HEAD~10 feature
git push orign feature --force
  • 通过squash命令压缩commit history
1
2
3
4
5
6
7
8
git reset --hard HEAD~12 # 将git指针定位到历史版本

git merge --squash HEAD@{1} # 从该点开始merge到最新的版本

git commmit -m "xxx" # 提交commit重写

git push origin master --force # 强制改写历史

分支管理

创建新分支

在创建新的local分支时,也可以添加commit hash告诉git分支最新的HEAD指向

1
2
git checkout -b feature
# create a branch based on current branch

切换分支/从Detached HEAD切换

1
git checkout feature

删除本地分支

1
2
git branch -d feature
git branch -D feature # force delete

删除远程分支

1
git push orgin --delete feature

合并分支

1
2
git merge feature
# merge changes from feature branch to current master branch

CherryPick别的分支commit/branch

在需要apply的分支上保证没有unstaged change,运行如下命令

1
git cherry-pick <commitHash>/<feature branch name>