This commit is contained in:
XyzBeta 2026-01-07 10:23:26 +08:00
commit 9a5394c7de
12 changed files with 2100 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

54
Dockerfile Normal file
View File

@ -0,0 +1,54 @@
FROM python:3.11-slim
# 设置国内镜像源 (Debian Bookworm)
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources \
&& sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list.d/debian.sources
# 安装系统依赖
# bash, curl, jq, git 是迁移脚本必须的
# tzdata 用于设置时区
RUN apt-get update && apt-get install -y \
bash \
curl \
jq \
git \
vim \
tzdata \
&& rm -rf /var/lib/apt/lists/*
# 设置时区为上海 (东八区)
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 设置工作目录
WORKDIR /app
# 安装 Python 依赖 (更换为阿里云源,清华源偶发 403)
RUN pip install flask requests -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
# 复制应用代码
COPY app.py .
COPY templates templates/
COPY static static/
COPY gitlab_migration.sh .
# 赋予脚本执行权限
RUN chmod +x gitlab_migration.sh
# --- Git 配置优化 (关键: 解决大仓库迁移失败) ---
# 1. 增大缓冲区到 500MB (默认仅 1MB),防止 send-pack 失败
RUN git config --global http.postBuffer 524288000
# 2. 设置低速超时: 只有当速度低于 1000 bytes/s 持续 600秒时才断开
# 调整回 600秒以适应超大仓库的传输
RUN git config --global http.lowSpeedLimit 1000 \
&& git config --global http.lowSpeedTime 600
# 创建数据目录 (用于挂载卷)
RUN mkdir -p migration_data
# 暴露端口
EXPOSE 5000
# 启动 Flask 应用
CMD ["python", "app.py"]

86
README.md Normal file
View File

@ -0,0 +1,86 @@
# GitLab Migration Tool
这是一个用于在两个 GitLab 实例之间迁移数据的自动化工具。它支持从旧版本 GitLab如 v12.x迁移到新版本如 v18.x涵盖用户、群组、项目、成员权限及 CI/CD 变量。
## 🚀 功能特性
- **全量迁移**支持用户、群组、项目含代码库、成员关系、CI/CD 变量的迁移。
- **Web 可视化界面**:提供直观的 Web 界面进行配置、连接测试和实时日志监控。
- **高性能**
- 项目迁移采用多进程并发执行。
- 支持 Git Mirror 镜像克隆与推送,保留完整提交历史、分支和标签。
- **幂等性设计**:支持断点续传。已迁移的对象(通过 ID 映射文件记录)会自动跳过,仅处理失败或新增的数据。
- **安全性**:对源 GitLab 环境强制只读,确保原始数据安全。
- **自动修正**:自动处理不合规的群组/项目路径Path和名称Name以适配新版 GitLab 的严格验证规则。
## 🛠️ 快速开始 (Docker 部署)
推荐使用 Docker Compose 快速启动服务。
### 1. 启动服务
```bash
docker-compose up -d --build
```
### 2. 访问 Web 界面
打开浏览器访问:[http://localhost:5555](http://localhost:5555)
### 3. 开始迁移
1. 在界面中输入 **源 GitLab****目标 GitLab** 的 URL 及 Access Token。
2. 点击 **"检查连接"** 确保双方网络和 Token 有效。
3. 选择迁移模式(默认 "全部迁移"),点击 **"开始迁移"**。
4. 在下方日志窗口实时查看迁移进度。
---
## 💻 命令行使用 (高级)
如果你更喜欢在终端操作,可以直接运行 Shell 脚本。
### 前置要求
- Linux/macOS 环境
- 已安装工具:`curl`, `jq`, `git`
### 运行脚本
```bash
# 设置环境变量 (可选,也可以直接修改脚本头部默认值)
export OLD_GITLAB_URL="http://old-gitlab.example.com"
export OLD_TOKEN="your-old-token"
export NEW_GITLAB_URL="http://new-gitlab.example.com"
export NEW_TOKEN="your-new-token"
# 运行迁移
# 模式可选: all, users, groups, projects, members, variables
./gitlab_migration.sh all
```
## ⚙️ 配置项说明
| 环境变量 | 说明 | 默认值 |
| :--- | :--- | :--- |
| `OLD_GITLAB_URL` | 源 GitLab 地址 | (需配置) |
| `OLD_TOKEN` | 源 GitLab 管理员 Token (Read API/Repo) | (需配置) |
| `NEW_GITLAB_URL` | 目标 GitLab 地址 | (需配置) |
| `NEW_TOKEN` | 目标 GitLab 管理员 Token (Full API) | (需配置) |
| `DEFAULT_PASSWORD` | 新建用户的默认密码 | `Password123!@#` |
| `MAX_JOBS` | 项目迁移并发进程数 | `5` |
| `SKIP_EXISTING_REPO` | 是否跳过已完成 Git 同步的项目 | `true` |
## ⚠️ 注意事项
1. **管理员权限**:建议使用 Admin 账号生成的 Access Token以确保能获取所有用户、群组和项目信息。
2. **用户密码**:由于 GitLab 安全机制,无法迁移用户原始密码。所有新迁移用户的初始密码将被设置为 `DEFAULT_PASSWORD` 配置的值(默认为 `Password123!@#`),并设置为“首次登录需修改密码”。
3. **数据映射**:迁移过程中会在 `migration_data/state` 目录下生成 ID 映射文件 (`.map`)。**请勿删除这些文件**,它们用于记录新旧 ID 的对应关系,是断点续传和成员权限恢复的基础。
4. **Git LFS**:脚本使用 `git clone --mirror`,理论上支持 LFS 对象,但取决于网络环境和 LFS 存储配置。
## 📂 目录结构
- `app.py`: Flask Web 应用后端。
- `gitlab_migration.sh`: 核心迁移逻辑脚本。
- `templates/` & `static/`: 前端界面资源。
- `migration_data/`: 存放迁移状态文件和临时数据Docker 卷挂载)。

150
app.py Normal file
View File

@ -0,0 +1,150 @@
from flask import Flask, render_template, request, Response, stream_with_context, jsonify, send_file
import subprocess
import os
import requests
import signal
app = Flask(__name__)
# 全局变量存储当前进程
current_process = None
# 默认配置
DEFAULT_CONFIG = {
"OLD_GITLAB_URL": os.environ.get("OLD_GITLAB_URL", "http://172.25.254.5:10088"),
"OLD_TOKEN": os.environ.get("OLD_TOKEN", "YJKiyTUEsfCpQ9yMSrwn"),
"NEW_GITLAB_URL": os.environ.get("NEW_GITLAB_URL", "http://172.23.24.8:32272"),
"NEW_TOKEN": os.environ.get("NEW_TOKEN", "glpat-jT8miNczJBRh9xRQbNoc"),
"DEFAULT_PASSWORD": os.environ.get("DEFAULT_PASSWORD", "Password123!@#"),
}
@app.route('/', methods=['GET'])
def index():
return render_template('index.html', config=DEFAULT_CONFIG)
@app.route('/check_connection', methods=['POST'])
def check_connection():
"""
检查与 GitLab 的连接状态
接收 form-data: url, token
"""
url = request.form.get('url')
token = request.form.get('token')
if not url or not token:
return jsonify({"status": "error", "message": "URL 或 Token 为空"})
try:
# 尝试请求 version 接口 (需要认证)
# 兼容旧版本可能没有 version 权限,尝试 user 接口
target_url = f"{url.rstrip('/')}/api/v4/user"
resp = requests.get(target_url, headers={"Private-Token": token}, timeout=5)
if resp.status_code == 200:
user_data = resp.json()
return jsonify({
"status": "success",
"message": f"连接成功! 当前用户: {user_data.get('username')} ({user_data.get('name')})"
})
elif resp.status_code == 401:
return jsonify({"status": "error", "message": "认证失败: Token 无效"})
else:
return jsonify({"status": "error", "message": f"连接失败 (HTTP {resp.status_code})"})
except Exception as e:
return jsonify({"status": "error", "message": f"请求异常: {str(e)}"})
@app.route('/download_log', methods=['GET'])
def download_log():
"""下载服务器端的迁移日志文件"""
log_file = os.path.join(os.getcwd(), 'migration.log')
if os.path.exists(log_file):
return send_file(log_file, as_attachment=True, download_name='migration.log')
else:
return "Log file not found", 404
@app.route('/stop', methods=['POST'])
def stop_migration():
"""停止当前正在运行的迁移任务"""
global current_process
if current_process and current_process.poll() is None:
try:
# 发送 SIGTERM 信号
current_process.terminate()
# 也可以尝试 kill: current_process.kill()
return jsonify({"status": "success", "message": "任务已发送停止信号"})
except Exception as e:
return jsonify({"status": "error", "message": f"停止失败: {str(e)}"})
else:
return jsonify({"status": "error", "message": "当前没有正在运行的任务"})
@app.route('/run', methods=['POST'])
def run_migration():
"""启动迁移任务 (SSE 流式输出)"""
global current_process
mode = request.form.get('mode', 'all')
# 如果已有任务在运行,拒绝新任务
if current_process and current_process.poll() is None:
return jsonify({"status": "error", "message": "已有任务正在运行,请先停止"}), 400
# 仅复制必要的环境变量,避免污染
env = os.environ.copy()
env.update({
'OLD_GITLAB_URL': request.form.get('old_url', ''),
'OLD_TOKEN': request.form.get('old_token', ''),
'NEW_GITLAB_URL': request.form.get('new_url', ''),
'NEW_TOKEN': request.form.get('new_token', ''),
'DEFAULT_PASSWORD': request.form.get('default_password', ''),
'PYTHONUNBUFFERED': '1', # 强制 Python 输出不缓冲
'MAX_JOBS': '5' # 并发数配置
})
def generate():
global current_process
cmd = ["./gitlab_migration.sh", mode]
yield f"data: 🚀 开始执行迁移任务: {mode} ...\n\n"
# 使用上下文管理器确保资源释放
try:
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
text=True,
bufsize=1 # 行缓冲
)
current_process = process
# 手动管理资源,不使用 with以便全局变量引用
try:
for line in process.stdout:
if line:
yield f"data: {line}\n\n"
return_code = process.wait()
if return_code == 0:
yield f"data: ✅ 迁移任务完成!\n\n"
elif return_code == -15: # SIGTERM
yield f"data: 🛑 迁移任务已手动停止。\n\n"
else:
yield f"data: ❌ 迁移任务失败 (Exit Code: {return_code})\n\n"
finally:
if process.stdout:
process.stdout.close()
if process.poll() is None:
process.terminate()
except Exception as e:
yield f"data: ❌ 系统错误: {str(e)}\n\n"
finally:
current_process = None
yield "event: close\ndata: closed\n\n"
return Response(stream_with_context(generate()), mimetype='text/event-stream')
if __name__ == '__main__':
# 生产环境建议关闭 debug
app.run(host='0.0.0.0', port=5000, debug=False)

16
docker-compose.yml Normal file
View File

@ -0,0 +1,16 @@
version: '3.8'
services:
gitlab-migration:
build: .
ports:
- "5555:5000"
volumes:
# 挂载数据目录以持久化状态文件 (id maps) 和日志
- ./migration_data:/app/migration_data
- ./migration.log:/app/migration.log
environment:
# 这里可以预设环境变量,也可以在 UI 中修改
- OLD_GITLAB_URL=http://172.25.254.5:10088
- NEW_GITLAB_URL=http://172.23.24.8:32272
# Token 建议在 UI 中输入,或者通过 .env 文件加载,不建议直接写在 yaml 中

1076
gitlab_migration.sh Executable file

File diff suppressed because it is too large Load Diff

5
static/css/bootstrap-icons.min.css vendored Normal file

File diff suppressed because one or more lines are too long

6
static/css/bootstrap.min.css vendored Normal file

File diff suppressed because one or more lines are too long

Binary file not shown.

Binary file not shown.

7
static/js/bootstrap.bundle.min.js vendored Normal file

File diff suppressed because one or more lines are too long

700
templates/index.html Normal file
View File

@ -0,0 +1,700 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GitLab 迁移助手专业版</title>
<!-- 使用本地静态资源 -->
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='css/bootstrap-icons.min.css') }}" rel="stylesheet">
<style>
:root {
/* 艳丽且专业的配色方案 */
--primary-color: #6c5ce7; /* 核心紫 */
--primary-light: #a29bfe; /* 浅紫 */
--secondary-color: #00b894; /* 活力绿 (成功状态) */
--accent-color: #0984e3; /* 科技蓝 */
--bg-color: #f1f2f6; /* 柔和背景灰 */
--text-main: #2d3436;
--text-muted: #636e72;
--card-radius: 12px;
--nav-height: 60px;
--footer-height: 40px;
}
body {
background-color: var(--bg-color);
font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
color: var(--text-main);
height: 100vh;
overflow: hidden; /* 禁止整页滚动,内容区域独立滚动 */
display: flex;
flex-direction: column;
margin: 0;
}
/* 进度条样式 */
.progress-bar-container {
height: 4px;
width: 100%;
background-color: #dfe6e9;
position: absolute;
top: 0;
left: 0;
z-index: 50;
}
.progress-bar-fill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--secondary-color), var(--accent-color));
transition: width 0.3s ease;
}
/* 1. 顶部导航栏 - 增加高度和质感 */
.navbar {
height: 64px; /* 回归标准高度 */
background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
flex-shrink: 0;
padding: 0;
z-index: 100;
}
.navbar-brand {
font-size: 1.35rem; /* 字体加大 */
font-weight: 700;
color: white !important;
display: flex;
align-items: center;
gap: 12px;
height: 100%;
letter-spacing: 0.5px;
}
/* 2. 主内容区域 - 核心布局逻辑 */
.main-wrapper {
flex: 1; /* 占满剩余高度 */
overflow: hidden; /* 防止溢出 */
padding: 20px 0; /* 上下留白 */
display: flex;
flex-direction: column;
}
.container-fixed {
width: 100%;
max-width: 1440px; /* 限制最大宽度,保证左右留白 */
margin: 0 auto;
padding: 0 30px; /* 左右留白 */
height: 100%; /* 继承父高度 */
display: flex;
gap: 25px; /* 左右分栏间距 */
}
/* 3. 分栏布局 - 独立滚动 */
.col-config {
width: 380px; /* 固定宽度,保证表单不被压缩 */
flex-shrink: 0;
display: flex;
flex-direction: column;
height: 100%;
}
.col-log {
flex: 1; /* 自适应剩余宽度 */
display: flex;
flex-direction: column;
height: 100%;
min-width: 0; /* 防止 Flex 子项溢出 */
}
/* 4. 卡片风格 - 悬浮与层次 */
.app-card {
background: white;
border-radius: var(--card-radius);
box-shadow: 0 8px 24px rgba(0,0,0,0.05);
display: flex;
flex-direction: column;
height: 100%; /* 占满列高 */
overflow: hidden; /* 内部滚动基础 */
border: 1px solid rgba(0,0,0,0.03);
transition: box-shadow 0.3s;
}
.app-card:hover {
box-shadow: 0 12px 32px rgba(0,0,0,0.08);
}
.card-header-custom {
padding: 15px 20px;
background: white;
border-bottom: 1px solid #f1f2f6;
font-weight: 700;
color: var(--text-main);
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
}
.card-header-custom i {
color: var(--primary-color);
margin-right: 8px;
font-size: 1.1rem;
}
/* 5. 滚动区域 - 隐藏滚动条但保留功能 */
.scrollable-content {
flex: 1;
overflow-y: auto;
padding: 20px;
}
/* 6. 表单元素优化 */
.config-group {
margin-bottom: 20px;
background: #fafbfc;
padding: 15px;
border-radius: 8px;
border: 1px solid #edf2f7;
}
.group-title {
font-size: 0.8rem;
font-weight: 700;
color: var(--text-muted);
text-transform: uppercase;
margin-bottom: 10px;
display: flex;
align-items: center;
gap: 6px;
}
.form-label {
font-size: 0.85rem;
font-weight: 600;
color: #4a5568;
margin-bottom: 4px;
}
.form-control {
font-size: 0.9rem;
padding: 8px 12px;
border-radius: 6px;
border: 1px solid #e2e8f0;
transition: all 0.2s;
}
.form-control:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 3px rgba(108, 92, 231, 0.1);
}
/* 7. 迁移模式选择器 - 视觉优化 */
.mode-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.btn-check:checked + .btn-outline-primary {
background-color: var(--primary-color);
border-color: var(--primary-color);
color: white;
box-shadow: 0 4px 10px rgba(108, 92, 231, 0.2);
}
.btn-outline-primary {
border-color: #e2e8f0;
color: var(--text-muted);
font-size: 0.85rem;
font-weight: 600;
padding: 8px;
}
.btn-outline-primary:hover {
background-color: #f8f9fa;
color: var(--primary-color);
border-color: var(--primary-color);
}
/* 8. 开始按钮 - 底部固定或随动 */
.btn-action {
background: linear-gradient(45deg, var(--primary-color), var(--accent-color));
border: none;
color: white;
width: 100%;
padding: 12px;
font-weight: 700;
border-radius: 8px;
margin-top: 10px;
transition: transform 0.2s;
}
.btn-action:hover {
transform: translateY(-2px);
box-shadow: 0 8px 20px rgba(108, 92, 231, 0.3);
color: white;
}
.btn-action:disabled {
background: #cbd5e0;
transform: none;
box-shadow: none;
}
/* 9. 日志窗口 - 终端风格 */
.terminal-window {
background-color: #1e272e;
color: #dcdde1;
flex: 1;
font-family: 'Fira Code', 'Consolas', monospace;
font-size: 13px;
padding: 20px;
line-height: 1.6;
overflow-y: auto;
white-space: pre-wrap;
border-radius: 0 0 var(--card-radius) var(--card-radius);
}
.terminal-header {
background-color: #2f3640;
padding: 8px 15px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid #353b48;
}
.status-badge {
font-size: 0.75rem;
padding: 4px 10px;
border-radius: 20px;
background: rgba(255,255,255,0.1);
color: #dcdde1;
}
.status-badge.active {
background: var(--secondary-color);
color: white;
}
/* 全屏模式样式 */
.fullscreen-overlay {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: #1e272e;
z-index: 2000;
display: flex;
flex-direction: column;
padding: 0;
}
.fullscreen-overlay .terminal-window {
border-radius: 0;
font-size: 14px;
}
/* 10. 底部版权 */
.footer {
height: var(--footer-height);
text-align: center;
color: #a4b0be;
font-size: 0.8rem;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.footer a { color: var(--primary-color); text-decoration: none; }
/* 响应式适配 */
@media (max-width: 992px) {
body { overflow: auto; height: auto; }
.container-fixed { flex-direction: column; height: auto; padding: 0 15px; }
.col-config, .col-log { width: 100%; height: auto; margin-bottom: 20px; }
.app-card { height: auto; overflow: visible; }
.terminal-window { height: 500px; }
}
</style>
</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-dark">
<div class="progress-bar-container">
<div id="progressBar" class="progress-bar-fill"></div>
</div>
<div class="container-fluid px-4">
<span class="navbar-brand">
<i class="bi bi-rocket-takeoff-fill fs-4"></i>
<span>GitLab 迁移助手</span>
</span>
<div class="d-flex align-items-center gap-3">
<span class="badge bg-warning text-dark" style="font-size: 0.8rem; font-weight: 700; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">PRO</span>
</div>
</div>
</nav>
<!-- 主体内容 -->
<div class="main-wrapper">
<div class="container-fixed">
<!-- 左侧配置栏 -->
<div class="col-config">
<div class="app-card">
<div class="card-header-custom">
<div><i class="bi bi-sliders"></i> 任务配置</div>
</div>
<div class="scrollable-content">
<form id="migrationForm">
<!-- 源环境 -->
<div class="config-group">
<div class="group-title text-primary d-flex justify-content-between">
<span><i class="bi bi-hdd-network"></i> 源环境 (Source)</span>
<button type="button" class="btn btn-sm btn-link p-0 text-decoration-none" onclick="checkConnection('old')">测试连接</button>
</div>
<div class="mb-3">
<label class="form-label">GitLab URL</label>
<input type="text" class="form-control" name="old_url" id="old_url" value="{{ config.OLD_GITLAB_URL }}" required>
</div>
<div>
<label class="form-label">Access Token</label>
<div class="input-group">
<input type="password" class="form-control" name="old_token" id="old_token" value="{{ config.OLD_TOKEN }}" required>
<button class="btn btn-outline-secondary border-start-0" type="button" onclick="togglePassword('old_token')"><i class="bi bi-eye"></i></button>
</div>
</div>
</div>
<!-- 目标环境 -->
<div class="config-group">
<div class="group-title d-flex justify-content-between" style="color: var(--accent-color)">
<span><i class="bi bi-hdd-network-fill"></i> 目标环境 (Target)</span>
<button type="button" class="btn btn-sm btn-link p-0 text-decoration-none" onclick="checkConnection('new')">测试连接</button>
</div>
<div class="mb-3">
<label class="form-label">GitLab URL</label>
<input type="text" class="form-control" name="new_url" id="new_url" value="{{ config.NEW_GITLAB_URL }}" required>
</div>
<div class="mb-3">
<label class="form-label">Access Token</label>
<div class="input-group">
<input type="password" class="form-control" name="new_token" id="new_token" value="{{ config.NEW_TOKEN }}" required>
<button class="btn btn-outline-secondary border-start-0" type="button" onclick="togglePassword('new_token')"><i class="bi bi-eye"></i></button>
</div>
</div>
<div>
<label class="form-label">Default Password</label>
<input type="text" class="form-control" name="default_password" value="{{ config.DEFAULT_PASSWORD }}" required>
</div>
</div>
<!-- 模式选择 -->
<div class="mb-3">
<label class="form-label mb-2"><i class="bi bi-list-check me-1"></i>迁移模式</label>
<div class="mode-grid">
<!-- 0. 全部 (首位) -->
<input type="radio" class="btn-check" name="mode" id="mode_all" value="all" checked>
<label class="btn btn-outline-primary w-100" for="mode_all" data-bs-toggle="tooltip" title="按顺序完整执行所有步骤">全部 (All)</label>
<!-- 1. 用户 -->
<input type="radio" class="btn-check" name="mode" id="mode_users" value="users">
<label class="btn btn-outline-primary w-100" for="mode_users" data-bs-toggle="tooltip" title="第一步: 迁移账号/密钥">用户 (Users)</label>
<!-- 2. 群组 -->
<input type="radio" class="btn-check" name="mode" id="mode_groups" value="groups">
<label class="btn btn-outline-primary w-100" for="mode_groups" data-bs-toggle="tooltip" title="第二步: 迁移群组结构">群组 (Groups)</label>
<!-- 3. 项目 -->
<input type="radio" class="btn-check" name="mode" id="mode_projects" value="projects">
<label class="btn btn-outline-primary w-100" for="mode_projects" data-bs-toggle="tooltip" title="第三步: 迁移代码库">项目 (Projects)</label>
<!-- 4. 成员 -->
<input type="radio" class="btn-check" name="mode" id="mode_members" value="members">
<label class="btn btn-outline-primary w-100" for="mode_members" data-bs-toggle="tooltip" title="第四步: 恢复成员权限">成员 (Members)</label>
<!-- 5. 变量 -->
<input type="radio" class="btn-check" name="mode" id="mode_variables" value="variables">
<label class="btn btn-outline-primary w-100" for="mode_variables" data-bs-toggle="tooltip" title="第五步: 迁移 CI/CD 变量">变量 (Variables)</label>
</div>
</div>
<div class="d-flex gap-2 mt-3">
<button type="button" class="btn btn-action flex-grow-1" onclick="startMigration()" id="runBtn">
<i class="bi bi-rocket-fill me-2"></i>开始执行迁移
</button>
<button type="button" class="btn btn-danger d-none" onclick="stopMigration()" id="stopBtn" style="margin-top: 10px; width: 80px;">
<i class="bi bi-stop-circle-fill"></i>
</button>
</div>
</form>
</div>
</div>
</div>
<!-- 右侧日志栏 -->
<div class="col-log">
<div id="logCard" class="app-card" style="background: #1e272e; border: none;">
<div class="terminal-header">
<div class="d-flex align-items-center gap-2">
<i class="bi bi-terminal-fill text-info"></i>
<span class="text-light fw-bold">TERMINAL OUTPUT</span>
</div>
<div class="d-flex align-items-center gap-2">
<span id="statusBadge" class="status-badge">READY</span>
<button class="btn btn-sm text-light hover-white p-0 ms-2" onclick="clearLog()" title="清空日志">
<i class="bi bi-eraser-fill"></i>
</button>
<a href="/download_log" target="_blank" class="btn btn-sm text-light hover-white p-0 ms-2" title="下载日志">
<i class="bi bi-download"></i>
</a>
<button class="btn btn-sm text-light hover-white p-0 ms-2" onclick="toggleFullscreen()" title="全屏显示">
<i id="fullscreenIcon" class="bi bi-arrows-fullscreen"></i>
</button>
</div>
</div>
<div id="logOutput" class="terminal-window">
<span style="color:#636e72">// 准备就绪...
// 请在左侧配置并启动任务。
// 日志将实时流式传输至此。</span>
</div>
</div>
</div>
</div>
</div>
<!-- 底部 -->
<footer class="footer">
<div>
&copy; 2025 XyzBeta - <a href="https://www.xyzbeta.com" target="_blank">www.xyzbeta.com</a>
</div>
</footer>
<!-- Scripts -->
<script src="{{ url_for('static', filename='js/bootstrap.bundle.min.js') }}"></script>
<script>
// Tooltip 初始化
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
// Auto-Save Config
document.addEventListener('DOMContentLoaded', function() {
// Restore from localStorage
const fields = ['old_url', 'old_token', 'new_url', 'new_token', 'default_password'];
fields.forEach(field => {
const storedValue = localStorage.getItem('gitlab_migration_' + field);
const element = document.getElementById(field);
if (storedValue && element) {
element.value = storedValue;
}
// Add listener to save on input
if (element) {
element.addEventListener('input', function(e) {
localStorage.setItem('gitlab_migration_' + field, e.target.value);
});
}
});
});
function togglePassword(id) {
const input = document.getElementById(id);
input.type = input.type === "password" ? "text" : "password";
}
function clearLog() {
if (confirm('确定要清空当前的日志输出吗?此操作不会删除服务器上的日志文件。')) {
document.getElementById('logOutput').innerHTML = '';
}
}
function checkConnection(target) {
const url = document.getElementById(target + '_url').value;
const token = document.getElementById(target + '_token').value;
const btn = event.target;
const originalText = btn.innerText;
if (!url || !token) {
alert('请先输入 URL 和 Token');
return;
}
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';
const formData = new FormData();
formData.append('url', url);
formData.append('token', token);
fetch('/check_connection', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
btn.disabled = false;
btn.innerText = originalText;
if (data.status === 'success') {
// 使用 Toast 或简单的 alert 提示成功
const icon = document.createElement('i');
icon.className = 'bi bi-check-circle-fill text-success ms-1';
// 移除旧图标
const oldIcon = btn.nextElementSibling;
if(oldIcon && oldIcon.tagName === 'I') oldIcon.remove();
btn.parentNode.insertBefore(icon, btn.nextSibling);
alert(data.message);
} else {
alert('连接失败: ' + data.message);
}
})
.catch(error => {
btn.disabled = false;
btn.innerText = originalText;
alert('系统错误: ' + error);
});
}
function toggleFullscreen() {
const card = document.getElementById('logCard');
const icon = document.getElementById('fullscreenIcon');
if (card.classList.contains('fullscreen-overlay')) {
card.classList.remove('fullscreen-overlay');
icon.classList.replace('bi-fullscreen-exit', 'bi-arrows-fullscreen');
} else {
card.classList.add('fullscreen-overlay');
icon.classList.replace('bi-arrows-fullscreen', 'bi-fullscreen-exit');
}
}
function startMigration() {
const form = document.getElementById('migrationForm');
const formData = new FormData(form);
const logWindow = document.getElementById('logOutput');
const btn = document.getElementById('runBtn');
const stopBtn = document.getElementById('stopBtn');
const statusBadge = document.getElementById('statusBadge');
const progressBar = document.getElementById('progressBar');
// UI 状态更新
btn.disabled = true;
btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> 执行中...';
stopBtn.classList.remove('d-none'); // 显示停止按钮
statusBadge.className = 'status-badge active';
statusBadge.innerText = 'RUNNING';
progressBar.style.width = '0%';
logWindow.innerHTML = '';
logWindow.innerHTML += '<span style="color:#a29bfe">--- 任务启动 ---</span>\n';
fetch('/run', {
method: 'POST',
body: formData
}).then(response => {
if (!response.ok) {
return response.json().then(err => { throw new Error(err.message) });
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
function read() {
reader.read().then(({ done, value }) => {
if (done) {
resetUI();
return;
}
const chunk = decoder.decode(value);
const lines = chunk.split('\n\n');
lines.forEach(line => {
if (line.startsWith('data: ')) {
let content = line.substring(6);
if (content.includes('closed')) return;
// 解析进度信息 PROGRESS: x / y
if (content.includes('PROGRESS:')) {
const match = content.match(/PROGRESS:\s+(\d+)\s+\/\s+(\d+)/);
if (match) {
const current = parseInt(match[1]);
const total = parseInt(match[2]);
if (total > 0) {
const percent = (current / total) * 100;
progressBar.style.width = percent + '%';
}
}
// 进度日志不显示在终端中,保持界面整洁
return;
}
// ANSI 颜色转换
content = content.replace(/\\033\[0;31m/g, '<span style="color:#ff7675">')
.replace(/\x1b\[0;31m/g, '<span style="color:#ff7675">')
.replace(/\\033\[0;32m/g, '<span style="color:#55efc4">')
.replace(/\x1b\[0;32m/g, '<span style="color:#55efc4">')
.replace(/\\033\[1;33m/g, '<span style="color:#ffeaa7">')
.replace(/\x1b\[1;33m/g, '<span style="color:#ffeaa7">')
.replace(/\\033\[0;34m/g, '<span style="color:#74b9ff">')
.replace(/\x1b\[0;34m/g, '<span style="color:#74b9ff">')
.replace(/\\033\[0;36m/g, '<span style="color:#81ecec">')
.replace(/\x1b\[0;36m/g, '<span style="color:#81ecec">')
.replace(/\\033\[0m/g, '</span>')
.replace(/\x1b\[0m/g, '</span>')
.replace(/\r/g, '');
logWindow.innerHTML += content + '\n';
logWindow.scrollTop = logWindow.scrollHeight;
}
if (line.includes('event: close')) {
reader.cancel();
resetUI();
}
});
read();
});
}
read();
}).catch(err => {
logWindow.innerHTML += `<span style="color:#ff7675">❌ 请求失败: ${err}</span>\n`;
resetUI();
});
function resetUI() {
btn.disabled = false;
btn.innerHTML = '<i class="bi bi-rocket-fill me-2"></i>开始执行迁移';
stopBtn.classList.add('d-none'); // 隐藏停止按钮
// 检查是否是因为停止而结束的
if (statusBadge.innerText !== 'STOPPED') {
statusBadge.className = 'status-badge active';
statusBadge.style.background = '#00b894';
statusBadge.innerText = 'FINISHED';
progressBar.style.width = '100%';
}
logWindow.scrollTop = logWindow.scrollHeight;
}
}
function stopMigration() {
if (!confirm('确定要强制停止当前任务吗?这可能会导致数据不完整。')) {
return;
}
const stopBtn = document.getElementById('stopBtn');
stopBtn.disabled = true;
fetch('/stop', { method: 'POST' })
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
// 状态更新逻辑由 SSE 结束事件处理,这里主要做标记
const statusBadge = document.getElementById('statusBadge');
statusBadge.style.background = '#ff7675';
statusBadge.innerText = 'STOPPED';
} else {
alert('停止失败: ' + data.message);
stopBtn.disabled = false;
}
})
.catch(err => {
alert('停止请求发送失败');
stopBtn.disabled = false;
});
}
</script>
</body>
</html>