GitLab Linux版自定义插件实践指南
一、先选对扩展方式
二、方式一 Webhooks 与外部服务
# pip install flask requests
from flask import Flask, request, jsonify
import requests
GITLAB_TOKEN = 'YOUR_PERSONAL_ACCESS_TOKEN'
GITLAB_URL = 'https://your-gitlab.example.com/api/v4'
@app.route('/webhook', methods=['POST'])
def handle():
data = request.get_json()
event = request.headers.get('X-Gitlab-Event')
print(f"Received {event}: {data.get('object_kind')}")
if event == 'Merge Request Hook':
project_id = data['project']['id']
mr_iid = data['object_attributes']['iid']
note_url = f"{GITLAB_URL}/projects/{project_id}/merge_requests/{mr_iid}/notes"
headers = {'Private-Token': GITLAB_TOKEN}
payload = {'body': 'Webhook 已收到并自动处理。'}
requests.post(note_url, headers=headers, json=payload)
return jsonify(ok=True)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
三、方式二 服务端钩子 System Hooks
四、方式三 Runner 自定义 Executor
echo '{"command": "run", "script": ["echo hello"]}' | ./my-executor
五、方式四 Ruby 插件扩展 GitLab 核心(高级)
module MyPlugin
class Engine < ::Rails::Engine
config.to_prepare do
require_dependency 'projects_controller'
class ProjectsController
before_action :add_custom_field, only: [:show]
def add_custom_field
@project.custom_field ||= "Default Value"
end
end
end
end
end