怎么使用 Git 向不同平台的仓库提交代码

场景描述:日常工作中,公司使用一个基于 gitlab 搭建的 Git 服务,我们自己写的小项目可能放在 Github、Coding 等平台上,不同平台的账户不同,如何便携的拉取、提交代码,而不用每次输入账号、密码呢?

1. 拉取代码

1.1. 方式一:用户名&密码

这种方式主要用于 HTTPS 协议。

➜  git clone https://用户名:密码@github.com/xxx.git

当用户名是邮箱时,如下:

# 这里的 %40 对应邮箱地址中的 @ 符号
➜ git clone https://aaaa%40gmail.com:密码@github.com/xxx.git

1.2. 方式二:SSH

这种方式主要用于 SSH 协议。

步骤:

  1. 生成对应 Git 的公私钥

    ➜  ssh-keygen -t rsa -C "email1@xxx.com” -f ~/.ssh/github_rsa
    ➜ ssh-keygen -t rsa -C "email2@xxx.com” -f ~/.ssh/coding_rsa
  2. 添加私钥

    ➜  ssh-add ~/.ssh/github_rsa
    ➜ ssh-add ~/.ssh/coding_rsa

    解决:Could not open a connection to your authentication agent

    ➜  ssh-agent bash

    其它命令:

    # 查看私钥列表
    ➜ ssh-add -l

    # 清空私钥列表
    ➜ ssh-add -D
  3. 添加对应不同平台的配置

    ➜  touch ~/.ssh/config
    ➜ vim ~/.ssh/config

    文件内容如下:

    # github
    Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/github_rsa

    # coding
    Host coding.net
    HostName coding.net
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/coding_rsa
  4. 将公钥添加到服务器

    这里以 Github 为例,首先拷贝对应的公钥。

    ➜  pbcopy < ~/.ssh/github_rsa.pub

    打开 https://github.com,找到设置中的 SSH and GPG keys,如下图:

    其中

    • Title 设置一个当前公钥的标识
    • Key 公钥复制到这里
  1. 测试连接

    ➜  ssh -T git@github.com
    Hi xxxxx! You've successfully authenticated, but GitHub does not provide shell access.

    测试 clone

    ➜  git clone git@xxx:xxx/demo.git

2. 提交代码

提交代码时,如果没有设置当前项目对应 Git 的 nameemail,将提示如下信息:

➜  git commit -m 'added file'

*** Please tell me who you are.

Run

git config --global user.email "you@example.com"
git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: empty ident name (for <>) not allowed

此时,我们需要使用以下命令,对当前项目添加本地设置:

# 注意,这里省略了参数 --local ,是针对当前项目的本地设置
➜ git config user.name "your git user name"
➜ git config user.email "yout git user email"

也可以使用如下命令查看设置结果:

# 查看本地设置
➜ git config --list --local

# 查看全局设置
➜ git config --list --global

再次重新提交代码即可。

⚠️ 注意:如果已经在 Git 的全局设置中添加 nameemail,在提交时会直接使用全局设置,而不会出现上面的提示信息。并且,之后在仓库中看到的提交人和邮箱也会是全局设置中的 nameemail, 所以一定要增加项目的本地设置,避免因使用默认全局设置而造成的提交信息混乱。