Ubuntu环境下GitLab插件开发指南
在Ubuntu系统上安装GitLab前,需完成基础环境准备:
sudo apt update && sudo apt upgrade -ysudo apt install -y curl openssh-server ca-certificates postfix(安装postfix时选择“Internet Site”,并填写服务器IP作为系统邮件名)。通过GitLab官方APT源安装GitLab Community Edition(CE):
curl -sS https://packages.gitlab.com/install/repositories/gitlab/gitlab-ce/script.deb.sh | sudo bashsudo apt install -y gitlab-cesudo gitlab-ctl reconfigure(生成默认配置)、sudo gitlab-ctl start(启动服务)。插件开发需通过GitLab API与核心功能交互,需创建访问令牌:
GitLab插件主要分为四类,可根据需求选择:
.gitlab/hooks下创建脚本(如post-receive)。#!/usr/bin/env python3
import requests
def send_notification(message):
url = "https://slack.com/api/chat.postMessage"
headers = {"Authorization": "Bearer YOUR_SLACK_TOKEN"}
data = {"channel": "#gitlab-notifications", "text": message}
requests.post(url, headers=headers, json=data)
if __name__ == "__main__":
send_notification("Code pushed to repository!")
chmod +x .gitlab/hooks/post-receive)。http://your-server/webhook)、触发事件(如Push、Merge Request)。from flask import Flask, request
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def handle_webhook():
data = request.json
print(f"Received event: {data['event_name']}")
return 'OK'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
sudo apt install -y ruby)、bundler(gem install bundler)。/opt/gitlab/embedded/service/gitlab-rails/plugins)创建新目录(如my_plugin),添加Gemfile(指定依赖)和lib目录(插件代码)。lib/my_plugin.rb):module MyPlugin
class Engine < ::Rails::Engine
config.to_prepare do
# 修改GitLab核心逻辑(如添加自定义字段)
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
gitlab-rails console加载插件并调试(require '/opt/gitlab/embedded/service/gitlab-rails/plugins/my_plugin/lib/my_plugin')。git push)触发脚本,验证执行结果。curl发送POST请求到Webhook URL,检查外部系统是否收到通知。gitlab-rails console调用插件方法,验证逻辑正确性。.gitlab/hooks目录或GitLab服务配置中,无需重启GitLab。gem build my_plugin.gemspec),上传到GitLab插件库,或通过gitlab-rails console安装(plugin.install('my_plugin'))。