常用的Git命令拾遗。

同步一个fork

场景:A同学fork了B同学的一个仓库,A在本地进行了修改,同时B也进行了修改。A这是想向B提交一个PR,那么需要先拉取B的更改,并合并到自己的仓库,然后再发起PR,那么如何同步呢。

1.将本地仓库关联到远程fork的那个仓库
使用命令:git remote -v查看远程,可以看到你只有自己仓库的地址:

1
2
3
$ git remote -v
origin git@github.com:abumaster/hello-world.git (fetch)
origin git@github.com:abumaster/hello-world.git (push)

那么要做的是,关联你foke的那个仓库地址,即设置上游地址:

1
2
3
4
5
6
git remote add upstream https://github.com/ckatgit/hello-world.git
$ git remote -v
origin git@github.com:abumaster/hello-world.git (fetch)
origin git@github.com:abumaster/hello-world.git (push)
upstream https://github.com/ckatgit/hello-world.git (fetch)
upstream https://github.com/ckatgit/hello-world.git (push)

2.同步上游代码的更新
拉取fork仓库的更新:

1
2
3
4
$ git fetch upstream
From https://github.com/ckatgit/hello-world
* [new branch] master -> upstream/master
* [new branch] readme-edits -> upstream/readme-edits

3.将更新合并到本地分支上
和本地分支合并一样的操作

1
2
git checkout master
git merge upstream/master

4.提交

1
git push origin master

5.创建PR
在github上提交PR申请即可。

!!现在已经可以在Github上直接进行操作了。

更改提交信息

使用场景:当你想修改提交信息的时候,就需要重写提交信息。

本地仓库提交了,未push的提交

使用命令:git commit --amend
输入信息,然后新的提交信息会写入到本地仓库中。

已经push的提交

首先,使用命令git commit --amend,输入新的提交信息后;
使用git push --force-with-lease强制推送经修改的旧提交。
不提倡强制推送,因为这会改变仓库的历史记录。 如果强制推送,已克隆仓库的人员必须手动修复其本地历史记录。

修改多个信息

如果需要修改多个提交或旧提交的消息,您可以使用交互式变基,然后强制推送以更改提交历史记录。

  1. 使用命令 git rebase -i HEAD~n,在编辑器中打开近n个提交记录;
    1
    2
    3
    4
    5
    6
    7
    8
    pick 3f9c9f5 :art: 优化导入
    pick f60559b readme
    pick c967995 延时队列-部分代码

    # Rebase e551850..c967995 onto e551850 (3 commands)
    #
    # Commands:
    # p, pick <commit> = use commit
  2. 在要更改的每个提交消息的前面,用reword替换 pick
  3. 保存并关闭提交列表文件;
  4. 在每个生成的提交文件中,键入新的提交消息,保存文件,然后关闭它;
  5. 使用git push --force强制推送。