一、問題
在github中遇到感興趣的項目,直接克隆下來,隨着興趣越來越濃,在本地做了些修改,后來干脆想fork到自己的github倉庫,又要把本地的修改提交到fork后的自己的github倉庫中。這時就遇到了git倉庫的遷移問題。
二、解決
1. 使用Git命令行操作如下
先查看remote的名字
git branch -r
假設你的remote是origin,用git remote set_url 更換地址
git remote set-url origin remote_git_address
remote_git_address更換成你的新的倉庫地址。
2. 使用 IntelliJ IDEA界面化操作,步驟如下:
(1)本地clone自GitHub某開源項目到本地
(2)在本地修改了一些內容
如下,藍色標題的Java代碼即為經過修改的。然后對項目產生興趣,fork到自己的GitHub倉庫中,並想將這些修改提交到自己的GitHub倉庫中。

(3)在GitHub中Fork該項目
(4)在本地設置Git遠程地址
如下,右鍵項目》Git》Repository》Remotes

(5)編輯現有地址,為自己的GitHub Fork該項目后產生的地址


(6)直接進行Commit/push操作,即會推送到自己的倉庫中。
三、參考
Git倉庫遷移而不丟失log的方法
- 要求能保留原先的commit記錄,應該如何遷移呢?
- 同時,本地已經clone了原倉庫,要配置成新的倉庫地址,該如何修改呢?
- 注意:如果使用了代碼審核工具Gerrit,那么在進行操作之前需要將Gerrit關掉,等成功恢復后再將Gerrit開戶即可
1、使用git push --mirror
先了解一些git的基本參數介紹
git clone --bare
GIT-CLONE(1) Git Manual GIT-CLONE(1)
NAME
git-clone - Clone a repository into a new directory
SYNOPSIS
git clone [--template=<template_directory>]
[-l] [-s] [--no-hardlinks] [-q] [-n] [--bare] [--mirror]
[-o <name>] [-b <name>] [-u <upload-pack>] [--reference <repository>]
[--depth <depth>] [--recursive] [--] <repository> [<directory>]
--bare
Make a bare GIT repository. That is, instead of creating <directory> and placing the administrative files
in <directory>/.git, make the <directory> itself the $GIT_DIR. This obviously implies the -n because there
is nowhere to check out the working tree. Also the branch heads at the remote are copied directly to
corresponding local branch heads, without mapping them to refs/remotes/origin/. When this option is used,
neither remote-tracking branches nor the related configuration variables are created.
git push --mirror
--mirror
Instead of naming each ref to push, specifies that all refs under refs/ (which includes but is not limited
to refs/heads/, refs/remotes/, and refs/tags/) be mirrored to the remote repository. Newly created local
refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and
deleted refs will be removed from the remote end. This is the default if the configuration option
remote.<remote>.mirror is set.
1、建立新倉庫
- 1). 從原地址克隆一份裸版本庫,比如原本托管於 GitHub,或者是本地的私有倉庫
git clone --bare git://192.168.10.XX/git_repo/project_name.git
- 2). 然后到新的 Git 服務器上創建一個新項目,比如 GitCafe,亦或是本地的私有倉庫,如192.168.20.XX
su - git
cd /path/to/path/
mkdir new_project_name.git
git init --bare new_project_name.git
- 3). 以鏡像推送的方式上傳代碼到 GitCafe 服務器上。
請確保已經添加了公鑰到新的機器上
cd project_name.git
git push --mirror git@192.168.20.XX/path/to/path/new_project_name.git
- 4). 刪除本地代碼
cd ..
rm -rf project_name.git
- 5). 到新服務器上找到 Clone 地址,直接Clone到本地就可以了。
git clone git@192.168.20.XX/path/to/path/new_project_name.git
這種方式可以保留原版本庫中的所有內容。
2、切換remote_url
先查看remote的名字
git branch -r
假設你的remote是origin,用git remote set_url 更換地址
git remote set-url origin remote_git_address
remote_git_address更換成你的新的倉庫地址。
第二種切換remote_url的方法更直接,直接更改.git/conf配置文件里的ip地址就行。