Git
安装
核心概念
author vs committer: author 代码是谁编写, committer 是谁合并/提交代码到仓库
head: TBD.
origin: TBD.
upstream: TBD.
stash: TBD.
常用配置
如无特别说明,以下以使用 Github 托管代码为例。
全局配置文件路径
macOS 和 Linux $HOME/.gitconfig Windows %USERPROFILE%\.gitconfig
直接添加或修改文件 .gitconfig 修改全局通用配置
# 设置 author 用户名和邮件地址
[user]
name = Zhang San
email = 12345678+san123456@users.noreply.github.com
[init]
# 默认分支名为 master,不用 main
defaultBranch = master
[core]
# 禁止自动转换文件换行符(CRLF/LF),编辑器保存文件是什么就是什么,要修改用户自己手动修改
autocrlf = false
# 忽略文件权限变更
fileMode = false
# 通过代理访问 Github
[https "https://github.com"]
proxy = socks5h://192.168.1.100:7890注意:Github 上可在 profile 设置 Name ,这个值如果和 gitconfig user.name 不一致,那么通过 Github 网页操作 pr / commit 时会替代 author 值。
在仓库执行 git shortlog -nse 统计时,可能会出现相同邮件地址的 committer 显示为不同的两个 committer(因为 user name 不一样)
266 Zhang San <12345678+san123456@users.noreply.github.com>
4 San <12345678+san123456@users.noreply.github.com>修改 Name 和 gitconfig 一致可以避免这个问题。如果想篡改历史中记录修复,见后面「常见用法」中「篡改历史」说明。
通过命令行设置或修改用户名和邮件地址
git config --global user.name "Zhang San"
git config --global user.email 12345678+san123456@users.noreply.github.comGithub 认证方式 SSH vs HTTPS
优势 劣势
SSH 配置公私钥后,提交或拉取代码时不需要手动输入密码 无法使用 HTTPS 代理
HTTPS 可使用 HTTPS 代理提交或拉取代码 需提前预先配置 HTTP 认证信息配置 Github HTTPS 认证信息步骤
在 Github settings 生成 token
修改全局配置文件 .gitconfig,补充以下
[url "https://<github用户名>:<github token值>@github.com"]
insteadOf = https://github.com常见用法
克隆仓库指定版本快照 git clone --depth 1 --branch v1.2.3 https://github.com/foo/bar.git $GOPATH/src/github.com/foo/bar
统计提交者信息 git shortlog -nse
push 到 fork 的 pr git push git@github.com:user/repo local_branch_name:remote_branch_name
从所有历史中删除指定敏感数据
brew install git-filter-repo
git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
cd YOUR-REPOSITORY
git filter-repo --invert-paths --path PATH-TO-YOUR-FILE-WITH-SENSITIVE-DATA
echo "YOUR-FILE-WITH-SENSITIVE-DATA" >> .gitignore
git add .gitignore
git commit -m "Add YOUR-FILE-WITH-SENSITIVE-DATA to .gitignore"
git remote add origin https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
git push origin --force --all
git push origin --force --tags参考
合并两个仓库
合并 project-a 入 project-b
cd path/to/project-b
git remote add project-a /path/to/project-a
git fetch project-a --tags
git merge --allow-unrelated-histories project-a/master # or whichever branch you want to merge
git remote remove project-a注:可能会触发大量冲突需要手动合并。
发布版本和打标签
列出标签 git tag -l
看标签详情 git show v0.0.1
打标签 git tag -a <tag name, such as v0.0.1> -m "description ..."
删除标签 git tag -d <tag name>
推送标签到上游 git push --tags
修改已有标签 git tag v0.0.35 -f -a
修改已有标签后推送到上游覆盖已有的 git push --tags -f
Push code to gitlab with access token
- Create a Project Access Tokens, http://10.0.0.1:8080/foo/bar/-/settings/access_tokens
- Add remote
git remote add xxx http://<TokenName>:<TokenValue>@10.0.0.1:8080/foo/bar.git - Push code
git push xxx master
https://stackoverflow.com/questions/42074414/gitlab-push-to-a-repository-using-access-token
篡改历史
TBD.
