【笔记】使用git管理代码
笔记
1. 配置git:
- 改变全局的用户邮箱:
git config --global user.email YourName@YourEMail.com - 改变全局的用户名:
git config --global user.name YourName - 在某一个repo里改变局域的用户邮箱:
git config --local user.email YourName@YourEMail.com - 在某一个repo里改变局域的用户名:
git config --local user.name YourName
2. 下载已有的git仓库
注意:以下指令中的gitlab.GitServer.com需要换成你自己的gitlab服务器域名。
- 以前github支持以下方式拉取代码,当前已经不支持。gitlab依然支持这种方式:
git clone https://gitlab.GitServer.com/user_name/project_name.git - 如果想在本地给repository指定名字:
git clone https://gitlab.GitServer.com/user_name/project_name.git local_name
3. 分支相关操作
a. 列出分支(branch)
git branch -a# 列出所有分支,含本地和远程git branch -r# 只列出远程的分支git branch# 只列出本地的分支
b. 删除local branch
git branch -d branch-name
或者使用git branch -D branch-name强制删除
c. 删除remote branch
git push origin --delete remote-branch-name
d. push到远程
git push origin remote-branch-name 注:origin是给远程设置的名字,可以有其他名字
e. 创建分支
git checkout -b branch-name# 常规用法git checkout -b branch-name commit-id# 从某一个commit-id创建分支
f. 从远程下branch
git checkout -b local-branch-name remote/branch-name
4. commit相关操作
git commit提交的时候有很多可选的参数配置,下面列举一些常用的用法:
git commit -m "commit message"# 如果不加-m "commit message",会弹出文本编辑器要求输入commit的信息git commit --author="YourName <YourName@YourEMail.com>"# 指定提交commit的作者信息
5. tracked repositories
git remote -v
git remote add upstream git_url
git push --set-upstream "origin(remote)" remote-branch-name
git reset --soft origin/master
https://help.github.com/articles/fork-a-repo/#platform-linux
- Syncing a fork
https://help.github.com/articles/syncing-a-fork/
6. 已经push到远程的最近一个commit强制删除
【危险操作,不建议做!!!】
先reset到前一个commit:git reset --hard HEAD~1
然后强制push:git push --force [origin remote-branch-name]
https://www.cnblogs.com/code1992/p/8974896.html
7. merge部分文件的修改到master分支
- 如何从其他分支merge个别文件或文件夹
https://segmentfault.com/a/1190000008360855
8. 修改历史提交中的作者名字或邮箱
【危险操作,对于多人合作的项目不要这么做!!!】
git rebase -i HEAD~4# 修改前4个commits提交,所以对前面的4个commits做rebase- 这时,你的文本编辑器会打开:将pick修改为edit
git commit --amend --author="YourName <YourName@YourEMail.com>" --no-editgit rebase --continue- 重复以上commit amend和rebase continue的两个步骤直到所有的修改均完成
https://www.git-tower.com/learn/git/faq/change-author-name-email
参考资料
- Interesting explanation about git
https://git-scm.com/book/en/v2
后记
本文最早发表在新浪博客【原文链接】。当时我把新浪博客当作个人笔记使用,2022年4月新浪博客已关闭访问,标志着一个时代的结束。