feat: 初始提交 - Code Server Bridge完整实现

- OAuth认证系统(Gitea + Lua扩展)
- Git自动化操作(本地/SSH远程)
- 实时进度WebSocket推送
- 现代化Tab界面UI
- Cobra CLI命令行(init/version/serve)
- 完整构建系统(Makefile + Taskfile)
- UPX压缩支持(体积减少70%)
This commit is contained in:
2026-01-08 23:32:29 +08:00
commit 8265df0dcd
40 changed files with 3786 additions and 0 deletions

View File

@@ -0,0 +1,630 @@
package handlers
import (
"crypto/sha1"
"cs-bridge/internal/config"
gitpkg "cs-bridge/pkg/git"
"cs-bridge/pkg/logger"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"path"
"strings"
)
// GitProgressPage 显示git进度页面
func GitProgressPage() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 获取repo参数
repo := r.URL.Query().Get("repo")
if repo == "" {
http.Error(w, "Missing repo parameter", http.StatusBadRequest)
return
}
// 返回HTML页面
w.Header().Set("Content-Type", "text/html; charset=utf-8")
logger.GetLogger().Info(fmt.Sprintf("[GitProgressPage] Repo参数: %s", repo))
// 使用字符串替换避免fmt格式化问题
html := strings.Replace(gitProgressHTML, "{{REPO_URL}}", repo, 1)
w.Write([]byte(html))
}
}
// ExecuteGitRequest 执行git操作的请求结构
type ExecuteGitRequest struct {
RepoURL string `json:"repo_url"`
}
// ExecuteGitResponse 执行git操作的响应结构
type ExecuteGitResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
RedirectURL string `json:"redirect_url,omitempty"`
Error string `json:"error,omitempty"`
}
// ExecuteGitOperations 执行git操作(克隆或更新)
func ExecuteGitOperations(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 解析请求
var req ExecuteGitRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
SendProgressJSON(w, "error", "Invalid request", 0)
return
}
if req.RepoURL == "" {
SendProgressJSON(w, "error", "Missing repo_url", 0)
return
}
log := logger.GetLogger()
log.Info(fmt.Sprintf("[ExecuteGit] 开始执行Git操作, RepoURL: %s, ClientIP: %s", req.RepoURL, r.RemoteAddr))
// 生成workspace路径 - 使用客户端IP和仓库URL的SHA1哈希作为workspaceID
repoName := gitpkg.GetRepoName(req.RepoURL)
// 基于客户端IP和仓库URL生成稳定的workspaceID
// hashInput := r.RemoteAddr + ":" + req.RepoURL
hashInput := req.RepoURL
hasher := sha1.New()
hasher.Write([]byte(hashInput))
workspaceID := hex.EncodeToString(hasher.Sum(nil))[:16] // 取前16位
log.Info(fmt.Sprintf("[ExecuteGit] 生成workspaceID: %s (基于: %s)", workspaceID, hashInput))
// 容器内路径(传递给code-server) - 使用path.Join确保Linux风格路径
containerWorkspacePath := path.Join(cfg.CodeServer.WorkspaceRoot, workspaceID, repoName)
// SSH服务器上的实际路径(用于git操作) - 使用path.Join确保Linux风格路径
sshWorkspacePath := containerWorkspacePath
if cfg.CodeServer.SSHWorkspaceRoot != "" {
sshWorkspacePath = path.Join(cfg.CodeServer.SSHWorkspaceRoot, workspaceID, repoName)
}
log.Info(fmt.Sprintf("[ExecuteGit] 路径配置 - Container: %s, SSH: %s", containerWorkspacePath, sshWorkspacePath))
// 进度回调函数
progressCallback := func(message string, percent int) {
SendProgressToClients("processing", message, percent)
}
// 检查是否使用SSH远程执行
useSSH := cfg.CodeServer.SSHHost != ""
var sshCfg gitpkg.SSHConfig
if useSSH {
sshCfg = gitpkg.SSHConfig{
Host: cfg.CodeServer.SSHHost,
Port: cfg.CodeServer.SSHPort,
User: cfg.CodeServer.SSHUser,
KeyPath: cfg.CodeServer.SSHKeyPath,
}
}
// 检查仓库是否存在
SendProgressToClients("checking", "正在检查仓库...", 5)
var err error
var repoExists bool
if useSSH {
repoExists = gitpkg.CheckRepoExistsRemote(sshCfg, sshWorkspacePath)
} else {
repoExists = gitpkg.CheckRepoExists(containerWorkspacePath)
}
if repoExists {
// 仓库存在,执行pull
SendProgressToClients("pulling", "仓库已存在,正在更新...", 20)
if useSSH {
err = gitpkg.PullRepoRemote(sshCfg, sshWorkspacePath, progressCallback)
} else {
err = gitpkg.PullRepo(containerWorkspacePath, progressCallback)
}
} else {
// 仓库不存在,执行clone
SendProgressToClients("cloning", "仓库不存在,正在克隆...", 20)
if useSSH {
err = gitpkg.CloneRepoRemote(sshCfg, req.RepoURL, sshWorkspacePath, progressCallback)
} else {
err = gitpkg.CloneRepo(req.RepoURL, containerWorkspacePath, progressCallback)
}
}
if err != nil {
SendProgressToClients("error", fmt.Sprintf("Git操作失败: %v", err), 0)
json.NewEncoder(w).Encode(ExecuteGitResponse{
Success: false,
Error: err.Error(),
})
return
}
// Git操作成功,发送100%进度
SendProgressToClients("success", "操作完成,即将跳转...", 100)
// 直接重定向到code-server,带folder参数
redirectURL := fmt.Sprintf("%s?folder=%s", cfg.CodeServer.BaseURL, containerWorkspacePath)
log.Info(fmt.Sprintf("[ExecuteGit] 准备重定向到: %s", redirectURL))
// 返回成功响应
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(ExecuteGitResponse{
Success: true,
Message: "Git操作完成",
RedirectURL: redirectURL,
})
}
}
// gitProgressHTML 是git进度页面的HTML模板
const gitProgressHTML = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>准备工作区 - Loading...</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
}
.container {
max-width: 700px;
width: 90%;
background: rgba(255, 255, 255, 0.15);
backdrop-filter: blur(20px);
border-radius: 25px;
padding: 50px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4), 0 0 100px rgba(255, 255, 255, 0.1) inset;
border: 1px solid rgba(255, 255, 255, 0.2);
animation: slideUp 0.6s ease-out;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
h1 {
text-align: center;
margin-bottom: 35px;
font-size: 32px;
font-weight: 700;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
letter-spacing: -0.5px;
}
.progress-container {
background: rgba(0, 0, 0, 0.25);
border-radius: 50px;
height: 24px;
overflow: hidden;
margin-bottom: 25px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2) inset;
}
.progress-bar {
background: linear-gradient(90deg, #4CAF50 0%, #8BC34A 50%, #CDDC39 100%);
height: 100%;
width: 0%;
transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 50px;
position: relative;
overflow: hidden;
}
.progress-bar::after {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
animation: shimmer 2s infinite;
}
@keyframes shimmer {
to {
left: 100%;
}
}
.status {
text-align: center;
font-size: 18px;
margin-bottom: 25px;
min-height: 30px;
font-weight: 500;
}
.log-container {
background: rgba(0, 0, 0, 0.35);
border-radius: 15px;
padding: 25px;
max-height: 350px;
overflow-y: auto;
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Courier New', monospace;
font-size: 13px;
line-height: 1.6;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.log-container::-webkit-scrollbar {
width: 8px;
}
.log-container::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.2);
border-radius: 4px;
}
.log-container::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.3);
border-radius: 4px;
}
.log-container::-webkit-scrollbar-thumb:hover {
background: rgba(255, 255, 255, 0.5);
}
.log-entry {
margin-bottom: 10px;
opacity: 0;
animation: fadeIn 0.4s ease-out forwards;
padding-left: 8px;
border-left: 2px solid transparent;
transition: all 0.3s ease;
}
.log-entry:hover {
background: rgba(255, 255, 255, 0.05);
border-left-color: rgba(255, 255, 255, 0.4);
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(-5px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.spinner {
display: inline-block;
width: 18px;
height: 18px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
vertical-align: middle;
margin-right: 8px;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.error {
color: #ff5252;
font-weight: 600;
}
.success {
color: #4CAF50;
font-weight: 600;
}
/* Tab导航 */
.tab-navigation {
display: flex;
gap: 10px;
margin-bottom: 30px;
border-bottom: 2px solid rgba(255, 255, 255, 0.2);
}
.tab-button {
flex: 1;
padding: 15px 20px;
background: transparent;
border: none;
color: rgba(255, 255, 255, 0.6);
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
border-bottom: 3px solid transparent;
position: relative;
bottom: -2px;
}
.tab-button:hover {
color: rgba(255, 255, 255, 0.9);
}
.tab-button.active {
color: #fff;
border-bottom-color: #4CAF50;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
animation: fadeIn 0.4s ease-out;
}
/* 完成区域 */
.completion-section {
display: none;
margin-top: 30px;
padding-top: 30px;
border-top: 1px solid rgba(255, 255, 255, 0.2);
text-align: center;
}
.countdown-text {
font-size: 20px;
margin-bottom: 20px;
opacity: 0.9;
}
.countdown-number {
font-size: 64px;
font-weight: 700;
color: #4CAF50;
margin: 20px 0;
text-shadow: 0 2px 20px rgba(76, 175, 80, 0.4);
}
.redirect-button {
background: linear-gradient(135deg, #4CAF50 0%, #8BC34A 100%);
color: white;
border: none;
padding: 16px 48px;
font-size: 18px;
font-weight: 600;
border-radius: 50px;
cursor: pointer;
box-shadow: 0 4px 20px rgba(76, 175, 80, 0.4);
transition: all 0.3s ease;
}
.redirect-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 30px rgba(76, 175, 80, 0.6);
}
.redirect-button:active {
transform: translateY(0);
}
</style>
</head>
<body>
<div class="container">
<h1>🚀 准备工作区</h1>
<!-- Tab导航 -->
<div class="tab-navigation">
<button class="tab-button active" onclick="switchTab('progress')" id="tabProgress">
📊 进行中
</button>
<button class="tab-button" onclick="switchTab('complete')" id="tabComplete">
✅ 已完成
</button>
</div>
<!-- 进行中Tab -->
<div class="tab-content active" id="progressTab">
<div class="progress-container">
<div class="progress-bar" id="progressBar"></div>
</div>
<div class="status" id="status">
<span class="spinner"></span>
<span>正在连接...</span>
</div>
<div class="log-container" id="logContainer">
<div class="log-entry">等待服务器响应...</div>
</div>
</div>
<!-- 已完成Tab -->
<div class="tab-content" id="completeTab">
<div class="completion-section" style="display: block; margin-top: 0; padding-top: 0; border-top: none;">
<div style="font-size: 48px; margin-bottom: 20px;">✅</div>
<div style="font-size: 24px; margin-bottom: 30px; font-weight: 600;">工作区准备完成!</div>
<div class="countdown-text">即将跳转到 Code Server...</div>
<div class="countdown-number" id="countdown">3</div>
<button class="redirect-button" onclick="redirectNow()">
立即跳转 →
</button>
</div>
</div>
</div>
<script>
const repoURL = '{{REPO_URL}}';
const progressBar = document.getElementById('progressBar');
const status = document.getElementById('status');
const logContainer = document.getElementById('logContainer');
let ws;
let isCompleted = false;
function addLog(message, isError = false) {
const entry = document.createElement('div');
entry.className = 'log-entry' + (isError ? ' error' : '');
entry.textContent = '> ' + message;
logContainer.appendChild(entry);
logContainer.scrollTop = logContainer.scrollHeight;
}
function updateProgress(percent) {
progressBar.style.width = percent + '%';
}
function updateStatus(message, showSpinner = true) {
if (showSpinner) {
status.innerHTML = '<span class="spinner"></span><span>' + message + '</span>';
} else {
status.innerHTML = '<span>' + message + '</span>';
}
}
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsURL = protocol + '//' + window.location.host + '/ws/git-progress';
ws = new WebSocket(wsURL);
ws.onopen = function() {
addLog('WebSocket连接已建立');
// 连接建立后,开始执行git操作
executeGitOperation();
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
addLog(data.message);
updateProgress(data.percent);
if (data.status === 'error') {
updateStatus('❌ ' + data.message, false);
status.className = 'status error';
} else if (data.status === 'success') {
updateStatus('✅ ' + data.message, false);
status.className = 'status success';
isCompleted = true;
} else {
updateStatus(data.message, true);
}
};
ws.onerror = function() {
addLog('WebSocket连接错误', true);
};
ws.onclose = function() {
addLog('WebSocket连接已关闭');
};
}
function executeGitOperation() {
updateStatus('正在执行Git操作...', true);
addLog('开始Git操作: ' + repoURL);
fetch('/api/git/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
repo_url: repoURL
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
addLog('✓ 操作成功完成');
// 显示跳转页面
showRedirectPage(data.redirect_url);
} else {
addLog('✗ 操作失败: ' + data.error, true);
updateStatus('操作失败', false);
}
})
.catch(err => {
addLog('✗ 请求失败: ' + err.message, true);
updateStatus('请求失败', false);
});
}
// Tab切换函数
function switchTab(tabName) {
// 更新按钮状态
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
if (tabName === 'progress') {
document.getElementById('tabProgress').classList.add('active');
document.getElementById('progressTab').classList.add('active');
} else {
document.getElementById('tabComplete').classList.add('active');
document.getElementById('completeTab').classList.add('active');
}
}
// 显示完成页面并启动倒计时
let redirectUrl = '';
let countdownTimer = null;
function showRedirectPage(url) {
redirectUrl = url;
// 等待1秒让进度条停留在100%
setTimeout(() => {
// 切换到已完成tab
switchTab('complete');
// 启动3秒倒计时
let count = 3;
const countdownElement = document.getElementById('countdown');
countdownTimer = setInterval(() => {
count--;
if (count > 0) {
countdownElement.textContent = count;
} else {
clearInterval(countdownTimer);
redirectNow();
}
}, 1000);
}, 1000);
}
// 立即跳转
function redirectNow() {
if (countdownTimer) {
clearInterval(countdownTimer);
}
window.location.href = redirectUrl;
}
// 启动
connectWebSocket();
</script>
</body>
</html>`