Git本地项目添加到远程代码库

来源:互联网 发布:知乎经典回复 编辑:程序博客网 时间:2024/06/05 06:29

问题描述

有时候,你在本地新建了项目并进行了很多操作,而github/osc上也新建了项目。若你不想先clone项目,之后再将本地项目复制到clone项目里,而是直接将本地项目push到github上对应的项目中,该怎么操作?

解决方法1

1). 本地项目目录中,执行git init操作。如我在$HOME/Project/EasySpring目录中;

# cd Project/EasySpring   //进入项目目录# git init  //初始化本地仓库

2). 如果你想忽略某些文件,则可以新建.gitignore文件,并添加忽略的文件;
3). 将本地项目添加到本地仓库中

# git add . //将项目目录下的所有文件(除了忽略的)加入暂存区# git commit -m "初次提交"   //将暂存区中的文件添加到本次仓库

4). 在本地项目目录中,未本地项目添加远程仓库

//"origin"是远程仓库的别名(不是远程仓库项目的名字),默认为origin,可以随便取# git remote add origin ~~git@git.oschina.net:fake/fake.git~~    

你可以执行命令git remote -v 来查看本地项目连接的是哪个远程仓库地址。

5). 将本地仓库push到远程仓库上

//origin是第4步中的仓库别名,master是本地仓库的主干分支# git push origin master

这个时候常有报错。错误有如下:

# git push origin masterTo ~~git.oschina.net:fake/fake.git~~ ! [rejected]        master -> master (fetch first)error: failed to push some refs to 'git@git.oschina.net:fake/fake.git'hint: Updates were rejected because the remote contains work that you dohint: not have locally. This is usually caused by another repository pushinghint: to the same ref. You may want to first integrate the remote changeshint: (e.g., 'git pull ...') before pushing again.hint: See the 'Note about fast-forwards' in 'git push --help' for details.

意思是远程项目中包含本地未包含的文件。查看很多Blog,有直接

git push -f

强制推送。但是在测试时发现还是不行。

遂改为直接拉取远程的文件到本地,发现也还是不行,但提示了新的错误。

# git pull origin masterwarning: no common commitsremote: Counting objects: 4, done.remote: Compressing objects: 100% (4/4), done.remote: Total 4 (delta 0), reused 0 (delta 0)Unpacking objects: 100% (4/4), done.From ~~git.oschina.net:fake/fake~~ * branch            master     -> FETCH_HEAD * [new branch]      master     -> origin/masterfatal: refusing to merge unrelated histories

提示是不相关的拒绝了合并。再次查询Blog2后执行

# git pull origin master --allow-unrelated-histories

命令后可以合并。这时再次push本地项目(步骤5)就可以了。

参考资料


  1. http://www.cnblogs.com/yaoxc/p/3946280.html ↩
  2. https://stackoverflow.com/questions/37937984/git-refusing-to-merge-unrelated-histories ↩