# 从头开始：Redmine 和 Gitlab 的集成和联动

本文的操作将达成如下目的：

1. 在 Redmine 中查看 GitLab 仓库中的变更。
2. Redmine 中更新 Gitlab 仓库。
3. 利用 Git Commit Log 改变 Redmine 中的 Issue 状态。

## 工作环境

该过程在 Kubernetes 环境中完成。

Redmine：sameersbn/redmine:3.3.1
Gitlab：官方镜像

## Redmine 设置

### 系统仓库设置

以管理员身份登入 Redmine，进入 `Administration -> Repositories`（`settings?tab=repositories`）。

#### SCM

- Enabled SCM 中，我们要使用的 Gitlab，因此需要启用 Git 。如果 Git 不可选，则需要确认是否安装了 git，并在 Redmine 的 configuuration.yml 中进行设置。
- Fetch commits automatically：True，这个选项只是在用户打开仓库页面时候会获取仓库内容，别想多了。
- Enable WS for repository management：True
- Repository management WS API key：这里需要生成一个 API Key，用于后面的 WebHook 触发。

#### Commit 信息设置

- Referencing keywords：引用关键字，保持缺省即可，在 Commit 信息中加入 `refs #1`，信息中会有到 #1 Issue 的连接。
- 下面的表格中可以根据 Commit log 中的关键字对 Issue 进行更新（状态和进度），例如填写 fixed fixed %60 的话，代表 Commit 信息中如果出现 `fixed #1`，则会把 Issue #1 更新为 Fixed，进度推进到 60%。

### 为项目获取 Git 仓库

在 Redmine 能访问得到的路径中，使用 git 命令克隆仓库：`git clone --mirror git@github.com:git_user/project.git`

### 项目仓库设置

- 进入项目的仓库设置页面（`projects/[project-id]/settings/repositories`）
- 添加仓库
- 路径指向上个步骤中的本地仓库的位置。
- 保存。
- 在 `projects/[project-id]/repository` 中，现在就可以看到版本库和文件了，并可以进行 diff 等操作。

### 安装插件

接下来安装 Redmin 插件

> 该插件将在 Redmine 中运行，用来响应来自 Gitlab 的 Webhook Post 请求。

Github：`https://github.com/phlegx/redmine_gitlab_hook`

下载到 Redmine 的插件目录之后，重启 Redmine 即完成安装。

可以在 Redmine 的 `admin/plugins` 中看到这一新安装的插件。

进入 `settings/plugin/redmine_gitlab_hook`，选中 `All branches`。

## Gitlab 设置

Gitlab 的设置分两步，第一是将 Issue 管理功能从内置模块转为使用 Redmine，第二是利用 Webhook 在发生事件的时候，引发 Redmine 的仓库更新。

### Issue

进入 Gitlab 的项目服务设置页面：`[project-url]/services`，找到 redmine 的设置：

- Active：True
- Trigger：Push
- Project url：Redmine 中相关的项目地址，例如`http://redmine.local/projects/sample-project`
- Issues url：一般是 Project url + `issues`，例如`http://redmine.local/projects/sample-project/issues`
- New issue url：通常是 Issues url + `new`，例如`http://redmine.local/projects/sample-project/issues/new`

保存退出后，该项目的 Issue 相关连接就会转向 Redmine 中。（挺 Low 的。。）

### Webhook

Webhook 是 Gitlab 的事件触发系统，这里我们借助这一功能，同 Redmine 的 Gitlab 插件协作，触发 Redmine 的自动更新。

浏览项目的 Webhook 页面：`[project-url]/hooks`，新建一个，URL 栏目填写
`http://redmine-url/gitlab_hook?project_id=[project-id]&key=[repository-token]`，key 部分就是前文中提到的 Repository Token。

### 测试

Git clone 代码之后，进行修改，提交 Comment 中写入 fixed #1，看 Redmine 中的这一 Issue 是否发生更新。
