用git的那点事
Git
git config
Github现在上传代码一般使用两种方式,一个是ssh,一个是https。
ssh由于安全问题逐步增加了各种限制,最开始我使用的时候还可以密码登录上传。后来就必须要密钥,再到现在需要走443端口(不确定是22端口被ban了,还是安全的问题,还是代理的问题,反正最终结局是用了443端口的ssh)。
https则需要使用gpg key,本机需要有管理gpg key的软件(好像?)。我在Mac上Push我的代码,
先生成gpg key,然后按要求上传到github,就可以正常通过https push代码了。
Linux上gpg key的管理软件和git的配置有点说法,TBD。
git clone
1 | git submodule init |
GitHub through proxy
背景:使用git上传GitHub一般需要科学上网。如果直接使用ssh的登陆方式可能会被代理服务器拒绝,因为ssh要访问22号端口。
关于一个用户使用多个git账户
1 | git config --global user.name "公司" |
给私人 GitHub 单独配 SSH key
因为 user.name/user.email 只影响 commit 作者信息,
真正 push 到哪里、用哪个账号认证,很多时候还取决于 SSH key 或 HTTPS 凭证。
如果你的私人仓库要 push 到 GitHub,最好单独配一把私人 key。
生成私人 key
1 | ssh-keygen -t ed25519 -C "你的私人邮箱" -f ~/.ssh/id_ed25519_github_personal |
配置 ~/.ssh/config
1 | Host github-personal |
已 clone 的仓库怎么改?
1 | git remote set-url origin git@github-personal:user-name/repo.git |
Q&A
git如何checkout到某个tag?
最常用就两种方式:直接到该 tag(游离 HEAD),或从该 tag 新建分支继续开发。
1)更新并查看 tag
git fetch –tags # 从远端抓取最新的 tag
git tag -l # 列出所有 tag
git show v1.2.3 # 看看这个 tag 指向的提交和说明
2)直接切到某个 tag(游离 HEAD 模式)
1 | git checkout tags/v1.2.3 # 或者:git checkout v1.2.3 |
等价的新版命令:
git switch –detach v1.2.3
3)从 tag 建一个分支(推荐需要修改时用)
1 | git checkout -b hotfix/v1.2.3 v1.2.3 |
4)返回之前分支
1 | git switch - # 回到上一个分支 |
常见坑位与技巧
分支名与 tag 同名时,用 tags/<tag> 消歧:git checkout tags/v1.2.3
浅克隆想取到某个 tag:
git fetch –depth=1 origin tag v1.2.3
有子模块的项目切到旧 tag 后同步子模块:
git submodule update –init –recursive
只恢复某个文件到该 tag 版本(不切分支):
git restore –source v1.2.3 – path/to/file
切换前有未保存改动:先提交或 git stash -u。
git如何设置git commit模板,如何查看已有的git commit模板所在位置
下面给你一套最常用、够用的做法(含查看、设置、示例模板)。
一、如何设置 commit 模板
1)全局(所有仓库生效)
1 | # 1. 新建一个模板文件(放在 HOME 里最方便) |
2)仅当前仓库生效
把模板文件放进仓库(方便团队共享),例如:
1 | # 在仓库根目录创建模板 |
说明:这里用相对路径,Git 会相对仓库根目录解析;跨平台更稳的话建议用绝对路径。
3)仅本次提交临时使用一个模板
git commit -t path/to/template.txt
4)取消模板
git config –global –unset commit.template # 取消全局
git config –unset commit.template # 取消当前仓库
二、如何查看模板“所在位置/来源”
查看“最终生效”的模板路径:
git config –get commit.template
同时看到“定义来源”(全局/本地/系统配置文件路径):
1 | git config --show-origin --get commit.template |
全量搜索(若不确定有没有设置过):
git config –list –show-origin | grep -E ‘^.*commit.template’
三、一个好用的模板示例(可直接复制)
把下面内容保存为 ~/.gitmessage.txt 或仓库里的模板文件:
1 | # <type>(<scope>): <subject> |
提示:以 # 开头的行会在提交时被 Git 视为注释并忽略,不会进入最终提交说明。
四、常见问题小贴士
模板看不到?确保 git commit 时会打开编辑器(不要用 -m 覆盖)。
团队共享:把模板文件放仓库内(如 .github/commit_template.txt),
并在仓库的 .git/config 里配置 commit.template 为相对路径,或写一条团队文档让大家各自 git config。
VS Code 作为编辑器:
1 | git config --global core.editor "code --wait" |
需要我帮你把现有提交风格(Conventional Commits 等)固化成模板/校验规则(commitlint + Husky)的话,我可以直接给出可用的配置文件和命令。
