git 不同仓库间进行项目迁移

需求

将仓库A的某个branch的代码独立成为一个新的仓库B。并且提交的代码为当前分支最新的,且保留整个提交历史。这种需求对于git来说小菜一碟,可通过git remote命令来实现。

实现

  1. 拉取仓库A当前分支(例如 master 分支),保持其为最新的

    1
    2
    3
    4
    5
    6
    7
    8
    9
    git pull origin master  # 拉取远程master分支的代码

    注:origin 代表远程仓库,其指向当前仓库的git地址, git remote 可进行查看,如下:
    $ git remote
    origin

    $ git remote -v
    origin https://github.com/forgetST/blog.git (fetch)
    origin https://github.com/forgetST/blog.git (push)
  2. 创建仓库B(例如 test),若不存在

  3. 在仓库A(blog)中增加仓库B的远程地址,即git地址

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    # 当前只关联了一个远程仓库A
    $ git remote -v
    origin https://github.com/forgetST/blog.git (fetch)
    origin https://github.com/forgetST/blog.git (push)

    # 关联远程仓库B(test)
    # test只是别名,可以随意起,但不能与已有远程名同名,至于原因,大家都想自己是独一无二的吗^-^
    $ git remote add test https://github.com/forgetST/test.git

    # 仓库test已关联成功
    $ git remote -v
    origin https://github.com/forgetST/blog.git (fetch)
    origin https://github.com/forgetST/blog.git (push)
    test https://github.com/forgetST/test.git (fetch)
    test https://github.com/forgetST/test.git (push)
  4. 仓库A(blog)代码推送到仓库A(test)

    1
    2
    $ git push test master # 一般会失败,错误见附录
    $ git push -f test master # 强制推送,有风险,慎用

附录

git remote add 用法:

1
2
3
4
5
6
7
8
9
10
usage: git remote add [<options>] <name> <url>

-f, --fetch fetch the remote branches
--tags import all tags and associated objects when fetching
or do not fetch any tag at all (--no-tags)
-t, --track <branch> branch(es) to track
-m, --master <branch>
master branch
--mirror[=(push|fetch)]
set up remote as a mirror to push to or fetch from

*git push origin_name origin_branch出错 *

1
2
3
4
5
6
7
8
9
10
11
$ git push test master
To https://github.com/forgetST/test.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/forgetST/test.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

注:当前分支有改动,可新建新的分支进行推送,新建分支不能与推送的仓库已有分支重名。或者强制推送,加选项 -f,视情况而用(慎用)。
-------------本文结束感谢您的阅读-------------