初始化操作
- 安装git
- 配置账号
git config --global user.name "username" git config --global user.email "your_email@example.com"
1.我要开始写代码了,想要从一开始就记录版本,首先初始化git库
git init
2.我新建了一个文件test1.txt,想要进行版本记录
git add test1.txt
git commit -m "test1.txt"
3.我新建了一个文件test2.txt,想要进行版本记录,同时删除test1.txt
git add test2.txt
git rm test1.txt
git commit -m "test2.txt"
4.我想查看刚才的操作记录(一行显示一个版本)
git log
git log --oneline
5.我在test2.txt里记录了一种解题步骤,我现在想到另一种解题思路,准备试试,但不想删除原来的解题步骤,试试分支吧
git branch new_branch
git checkout new_branch
/*
do something on test2.txt
*/
git commit -m "test2.txt-new_branch"
6.我发现第二种解题方法更好,只想保留这一种,可以将分支的内容合并到主线
git checkout master
git merge new_branch
7.现在new_branch的内容已经合并到主线,我不需要它了,我们来删除分支
git branch -d new_branch
8.现在都是用的本地git库,如何把代码导入代码托管平台呢,以gitcode为例
首先得使用gitcode的账号再来一遍
git config --global user.name "username"
git config --global user.email "your_email@example.com"
方案一:本地无版本记录文件上传
git clone https://gitcode.com/mushike/test.git
/*
把本地无版本记录的代码拷到对应文件夹中
*/
git add test2.txt
git commit -m "初次上传"
git push
方案二:本地已有git库上传
/*
在本地git库所在文件夹执行
*/
git remote add origin https://gitcode.com/mushike/test.git
git push -u origin master
9.代码已上传gitcode,其他设备都可以从网络访问了,首先是clone,最后是push,中间和本地git库操作步骤一样
git clone https://gitcode.com/mushike/test.git
/*do something*/
git add <files>
git commit -m "commit modify"
git push
10.我上传了一个大文件(50M),commit成功了却无法push,这是由于托管平台的限制,默认10M,最大100M,同时还得使用lfs功能
git add bigfile
git commit -m "Add bigfile"
/*
此时push会报错
*/
git lfs install
git lfs track bigfile
git add .gitattributes
git commit -m "Track bigfile using Git LFS"
git push
11.如果是一个多文件的工程,只想要上传源文件,不需要编译生成的文件
可以使用.gitignore文件来实现,可以按后缀忽略,按文件夹忽略等,下边为一个.gitignore文件示例,之后再提交就会自动忽略.gitignore里的文件
build/
*.log
*.tmp
git add .gitignore
git commit -m "add .gitignore"
git push
12.之前版本记录的文件已有1.log,怎么去掉
git rm --cached 1.log
git commit -m "Remove file from version control"
git push
13.我从网上clone的源码,自己做了些修改,如何查看自己的改动内容
修改后的文件还没有使用git add
git diff file
已经git add过的文件
git diff --staged file
14.我修改的代码有效,想把这部分修改保存到文件中,可以使用补丁(patch)功能
代码还没提交也没git add
git diff > my_patch.diff
代码还没提交但git add后
git diff --staged > my_patch.diff
代码已提交(从8ec64f2到8ec64f2的修改)
git format-patch f823faf..8ec64f2 > my_patch.diff
git format-patch f823faf..8ec64f2 --stdout > my_patch.diff
应用补丁
git apply my_patch.diff
/*
git format-patch 生成的补丁
*/
git am < /path/to/patchfile.patch