GitLab 使用

351 阅读2分钟

GitLab 和 GitHub 的异同

相同点

  • github 和 gitlab 均是基于 git 实现的代码托管仓库. 不同点
  • github 使用私有仓库或者企业版, 均需要付费.
  • gitlab 使用私人仓库是免费的, 可用于在企业内搭建 git 私服.

GitLab 官网为 gitlab.com  

GitLab 使用

1. 创建项目

创建一个空项目

2. 配置 SSH Key

一般情况下, 如果我们同时使用多个 GitLab 账号或者 GitHub 账号, 我们需要分别为每个账号分配 SSH Key, 用于上传不同的项目.

第一步: 确认主账号(全局默认配置)

git config --global user.name 'test' && git config --global user.email 'testCompany@company.com'

第二步: 生成公钥和私钥

默认的ssh目录为~/.ssh下,

# 生成默认主账户
ssh-keygen -t rsa -C "testCompany@company.com"

# 生成副账号的公钥、密钥,同时指定文件名
ssh-keygen -t rsa -f ~/.ssh/id_rsa.github -C "testPeronal@personal.com"

第三步: 添加配置文件

# 进入 ssh 配置目录
cd ~/.ssh

# 新建 config 文件并配置 config 文件
touch config

新建好 config 配置文件后,添加如下内容到 config 配置文件中(副账号为 github),

Host *github.com
     IdentityFile ~/.ssh/id_rsa.github
     User testPeronal

第四步: 上传 SSH Key

登录 GitLab 账号 / GitHub 账号, 点击自己的头像 => setting => 添加 SSH Key, 比如 GitLab 的设置在这里.

复制 id_rsa.pub 的内容(公钥)上传. 下面的这个公钥就是我们单独创建的.

image.png

第五步: 测试连接

github ssh -T git@github.com 
gitlab ssh -T git@gitlab.com

如果出现相对应的账号名称, 则说明测试成功.

如果你在使用的过程中出现每次都需要你输入密码的问题

Enter passphrase for key '/Users/xxx/.ssh/id_rsa'

可以重新设置密码.

$ ssh-keygen -p

Enter file in which the key is (/Users/xxx/.ssh/id_rsa): /Users/xxx/.ssh/id_rsa.lcgitlab

1. 如果默认文件不是我们想改动的, 可以手动指定.
2. 修改的新密码如果为空, 则默认无密码.

3. 开始使用 GitLab

由于我是在原有GitLab账号下, 单独新建的一个 GitLab 副帐号, 所以我在使用的过程中需要手动配置本地仓库的用户名和密码, 不能使用全局的用户名和密码.

# 进入当前拉取或初始化的 gitlab 仓库
cd ${your-project}
# 设置本地仓库的用户名和邮箱
git config user.name "test" && git config user.email "test@personal.com"
设置全局账号和密码
git config --global user.name "test"
git config --global user.email "test@qq.com"

创建一个新的仓库
git clone git@gitlab.com:testName/xxx.git   
cd xxx
git switch -c main   // 切换为主分支
touch README.md
git add README.md
git commit -m "add README"
git push -u origin main   // 上传代码

==============最常用==============
push 将一个已存在的文件
cd xxx
git init --initial-branch=main   // 初始化仓库
git remote add origin git@gitlab.com:LinMaris/education_live.git  // 设置源
git add .
git commit -m "Initial commit"
git push -u origin main  // 上传代码

push 一个已存在的 Git 仓库
cd xxx
git remote rename origin old-origin   // 修改源的名称
git remote add origin git@gitlab.com:testName/xxx.git
git push -u origin --all          // 上传
git push -u origin --tags
查看远端分支
git branch -a

查看本地分支
git branch

切换分支
git checkout xxx
如果分支切换后, push代码的时候报错, 请确认当前使用的主分支名称. 可以尝试使用 pull 先拉取线上的代码, 再进行提交.
git pull origin xxx

删除一个 gitlab 项目

  1. 点击当前项目
  2. 点击 setting
  3. 点击 Advanced -> Expand.
  4. 界面拉到最下面, 删除该项目.

参考

如何使用ssh同时连接github和gitlab git命令-切换分支 git clone和git pull的区别