Featured image of post Git

Git

Config

最佳实践

1
2
3
4
5
6
7
git config --global rebase.autosquash true
git config --global alias.fixup 'commit --fixup'
git config --global alias.ri 'rebase -i'
git config --global alias.cm 'commit -m'
git config --global alias.lg 'log --graph --oneline --decorate --all'
git config --global alias.save '!git add . && git commit -m "WIP"'
git config --global alias.undo 'reset --soft HEAD^'

设置 GitHub 代理

1
git config --global http.https://github.com.proxy socks5://127.0.0.1:1080

pull.rebase

1
git config --global pull.rebase true

Tips

将修改的已跟踪文件添加到暂存区

1
git add -u

修改最新的 commit 信息

1
git commit --amend

拉取最新远程分支并合并

1
git pull [-p] [-r] origin <branch-name>

-p –prune, -r –rebase

Reset

  1. 重置 git add . 状态

    1
    
    git reset
    
  2. 撤销最新的 commit

    1
    
    git reset --soft HEAD^
    
  3. 撤销多个 commit

    1
    
    git reset --soft HEAD~n
    

Reflog

通过 git reflog 来查看所有的 commit,包括被 reset 掉的 commit。

1
git reflog

Cherry-pick

通过 git cherry-pick 来将某个 commit 应用到当前分支上。

1
git cherry-pick <commit-hash>

Diff

1
git diff <commit-start> [commit-end] [-- path/to/file] > diff.patch

path/to/file 可选,如果不指定则会比较整个项目的差异。

垃圾回收

清理无用的对象,优化存储空间和性能。

1
git gc --aggressive

Revert

1
git revert <commit-hash>

Revert merge commit

1
git revert -m 1 <commit-hash>

被 revert 过的分支合并若需要再次合并到主分支,需要将之前的 revert 也 revert 掉,否则该合并会不完整。

git log --oneline | grep "Revert" | grep "commit message"

可以通过这个命令来筛选出之前的 revert commit hash。

Branch Rename

1
2
3
4
git branch -m [old-branch-name] <new-branch-name>
git push --delete origin <old-branch-name>
# git branch --unset-upstream
git push --set-upstream origin <new-branch-name>

更改 .gitignore 后让 Git 忽略已经被跟踪的文件

1
2
3
4
git rm -r --cached .
git add .
git commit -m "update: .gitignore"
git push

Squash

1
git rebase -i <commit-hash>

pick -> squash,只保留第一个 pick,其他的 squash

开发流程

每次新的开发都需要从 main 分支新建一个分支,测试通过后发起 Pull request,由其他成员进行 Code review,通过后合并到 main 分支。

非必要情况下,不要直接在 main 分支上进行开发。main 分支采取分支保护并需要线性历史,禁止直接 push,只能通过 Pull request 合并, 且至少需要一个成员的 Approval 才能合并。

📝 备注

当然不一定只能从 main 分支新建分支,也可以从其他分支新建分支,但是最终都要合并到 main 分支。

develop

  1. git switch -c <new-branch-name>
  2. Coding
  3. git add .
  4. git commit -m "commit message"
  5. git push [--set-upstream] origin <new-branch-name>
  6. 在 develop 分支上发起 Pull request
  7. Code review
  8. Create a merge commit 到 develop 分支

production

  1. 在 main 分支上发起 Pull request
  2. Code review
  3. Squash amd merge 到 main 分支1
  4. git switch main
  5. git fetch --prune
  6. git pull
  7. git branch -D <new-branch-name>2

  1. 可选删除被合并的分支(可以通过代码托管平台删除也可以通过 git push origin --delete <new-branch-name> 删除) ↩︎

  2. 如果已经在代码托管平台删除远程分支,这条命令不用执行 ↩︎

CC BY-NC-SA 4.0