Git提交已有项目

如何把已有项目提交到Git上?

这个问题已困惑我多时,今天实在忍受不了折磨,找了下资料。总结一下。

基本方法

首先我是在码云上创建的Git项目,项目里就一个readme和gitignore文件。本地有个项目文件夹。

使用git bash 打开项目文件夹,然后执行下面几条语句。

1
2
3
4
5
6
touch README.md //新建说明文件
git init //在当前项目目录中生成本地git管理,并建立一个隐藏.git目录
git add . //添加当前目录中的所有文件到索引
git commit -m "first commit" //提交到本地源码库,并附加提交注释
git remote add origin 粘贴复制的地址 //添加到远程项目,别名为origin
git push -u origin master [第一次需要添加url不带这个括号的]//把本地源码库push到github 别名为origin的远程项目中,确认提交

创建.gitignore

  1. 在项目根目录下面创建gitignore.txt文件
  2. 把你需要排除的文件名保存到gitignore.txt文件
  3. 在项目根目录下面按住Shift键并邮件然后选择“在此处打开命令窗口”
  4. 执行命令 ren gitignore.txt .gitignore

错误Please tell me who you are

如果没有配置邮箱以及名字,可能提示Please tell me who you are.有两种方法可以配置邮箱以及名称

全局配置

1
2
git config --global user.email "you@example.com"
git config --global user.name "Your Name"

单独为某个项目配置
1.打开项目所在目录,找到隐藏的.git文件夹。
2.打开文件夹里的config文件。
3.添加这三行到文件:

1
2
3
[user]
name = XXX(自己的名称)
email = XXXX(邮箱)

也可以通过命令行的方式,只需要在 .git 文件夹下。 例如执行如下命令:

1
git config user.name "xxxxx"

错误Please enter a commit message

1、当出现上述情况,可按键盘左上角的“Ese”退出键;
2、输入“:wq”,注意是英文输入状态下的冒号,然后按下“Enter”键即可。
( “ :wq”是啥意思呢?学Linux操作系统时的命令: 强制性写入文件并退出。)

错误failed to push some refs to

原本到这里就结束了,但是呢,没有让我输入账号密码,而且我的项目并没有推到码云上面,还报错了。

1
2
3
4
5
6
error: failed to push some refs to 'https://github.com/dummymare/Hello-World.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.

就是上面这个错误提示。看样子问题不是很严重,主要是我看不懂是什么意思,我用sourcetree添加了工作副本。(因为项目文件夹下有.git文件了)

然后在sourcetree上再次提交(sourcetree有保存账号密码),中间不知道经历了什么,出了个新错误。

错误refusing to merge unrelated histories

感觉是因为原本码云上有文件,起了冲突。再次搜索资料,解决办法是

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

这样就ok了,把两个分支合并到一起了。

之后,我再次尝试在码云上创建一个空的git仓库什么文件都没有,然后随便找了一个项目文件夹执行之前的那几个步骤,没有报错。