换了自己的电脑去办公,遇到了自己私有仓库和公司代码仓库管理的问题


因为办公用的是自己的电脑,遇到了下面这种情况

公司的代码仓库使用云效,需要一个密钥来拉取代码
自己的私人代码仓库也使用了密钥,需要一个密钥来拉取和提交代码

这个时候就不能在本地直接生成两个密钥了,因为会覆盖

新建两个密钥,分别取名对应不同团队的代码仓库

# 操作前最好进入C:\Users\用户名\.ssh目录下,不然生成的密钥会在你当前打开Git bash的目录

# ====生成用于团队仓库的密钥
ssh-keygen -t rsa -C "lonelylizard@foxmail.com"

# 当提示Enter file in which to save the key (/c/Users/lonelylizard/.ssh/id_rsa)时输出一个别名来标识该密钥,不写默认名为id_rsa,这里我使用codeup_rrzu
codeup_rrzu
提示输入密码,如果不希望每次提交代码都提示输入密码则保持为空,回车两次即可

# ====生成私人仓库的密钥
ssh-keygen -t rsa -C "lonelylizard@foxmail.com"

# # 当提示Enter file in which to save the key (/c/Users/lonelylizard/.ssh/id_rsa)时输出一个别名来标识该密钥,如果上面团队仓库的密钥没填写,则这里一定要输入别名,否则会覆盖密钥,这里我使用codeup_sumver来标识
codeup_sumver

git配置.png

在git的配置文件config中编辑配置

在C:Users用户名.ssh找到并编辑config文件,如果没有则新建一个,输入以下内容

# ====config文件-开始=====
# 公司代码仓库
Host rrzu
HostName codeup.aliyun.com
IdentityFile ~/.ssh/codeup_rrzu
PreferredAuthentications publickey
User **龙
# 私人代码仓库
Host sumver
HostName codeup.aliyun.com
IdentityFile ~/.ssh/codeup_sumver_pri
PreferredAuthentications publickey
User sumver
# ====config文件-结束=====

填写说明:
Host:别名,这个等会用得到
HostName:托管平台服务地址
IdentityFile:刚才生成的密钥路径

绑定仓库,拉取、提交代码

在云效端新增一个空白的代码仓库
之后把自己的代码仓库根据如下步骤变为git仓库并绑定远端这个空白仓库
需要注意的时候,在进行git remote add origin 或者是git clone的时候,你拿到的ssh仓库代码地址如:

git@codeup.aliyun.com:abwertyuiodklsdsa/rrzu_order.git

不能直接Git clone或者git remote add origin
因为git不知道要使用哪个密钥去认证
需要把加粗部分替换为刚才在config文件配置的Host别名
团队代码仓库

git@codeup.aliyun.com:abwertyuiodklsdsa/rrzu_order.git

修改为

git@codeup_rrzu:abwertyuiodklsdsa/rrzu_order.git

具体操作步骤

cd 本地已有的代码仓库根目录
# 初始化为Git仓库
git init

# 本地仓库绑定远端仓库
git remote add origin 仓库链接

# 拉取远端仓库,必须加上--allow-unrelated-histories,否则后面提交代码会提示远端分支和本地分支没有关系而拒绝提交代码,出现合并说明填写窗口,按shift+:进入命令模式,输入wq退出
git pull origin master --allow-unrelated-histories

# 提交代码
git add .
git commit -m "提交说明"
git push origin master

此后,新代码仓库只要第一次拉取git clone或者绑定本地仓库git remote add的时候把代码仓库链接替换一下,后续的pull、push都可以直接使用,会自动使用正确的密钥去认证

文章目录