0
0

增加了git功能,但是还未完善

This commit is contained in:
xubing
2025-11-24 17:53:48 +08:00
parent 925024bce1
commit fa1e291bed
682 changed files with 131314 additions and 157 deletions

View File

@@ -1,8 +1,38 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigPanel = void 0;
// src/panels/ConfigPanel.ts
const vscode = require("vscode");
const vscode = __importStar(require("vscode"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const isomorphic_git_1 = __importDefault(require("isomorphic-git"));
const node_1 = __importDefault(require("isomorphic-git/http/node"));
const ProjectView_1 = require("./views/ProjectView");
const AircraftView_1 = require("./views/AircraftView");
const ContainerView_1 = require("./views/ContainerView");
@@ -26,11 +56,15 @@ class ConfigPanel {
this.currentProjectId = '';
this.currentAircraftId = '';
this.currentContainerId = '';
this.currentRepoId = '';
// 数据存储
this.projects = [];
this.aircrafts = [];
this.containers = [];
this.configs = [];
// Git 仓库存储
this.gitRepos = [];
this.currentRepoFileTree = [];
// 项目存储路径映射
this.projectPaths = new Map();
this.panel = panel;
@@ -40,6 +74,8 @@ class ConfigPanel {
this.aircraftView = new AircraftView_1.AircraftView(extensionUri);
this.containerView = new ContainerView_1.ContainerView(extensionUri);
this.configView = new ConfigView_1.ConfigView(extensionUri);
// 加载 Git 仓库数据
this.loadGitRepos();
this.updateWebview();
this.setupMessageListener();
this.panel.onDidDispose(() => {
@@ -48,6 +84,7 @@ class ConfigPanel {
}
setupMessageListener() {
this.panel.webview.onDidReceiveMessage(async (data) => {
console.log('📨 收到Webview消息:', data);
switch (data.type) {
case 'openExistingProject':
await this.openExistingProject();
@@ -84,6 +121,7 @@ class ConfigPanel {
this.currentProjectId = '';
this.currentAircraftId = '';
this.currentContainerId = '';
this.currentRepoId = '';
this.updateWebview();
break;
case 'goBackToAircrafts':
@@ -144,9 +182,354 @@ class ConfigPanel {
case 'deleteConfig':
await this.deleteConfig(data.configId);
break;
// Git 仓库管理功能
case 'fetchBranches':
console.log('🌿 获取分支列表:', data.url);
await this.fetchBranches(data.url);
break;
case 'cloneBranches':
console.log('🚀 克隆选中的分支:', data);
await this.cloneBranches(data.url, data.branches);
break;
case 'cancelBranchSelection':
console.log('❌ 取消分支选择');
this.updateWebview();
break;
case 'loadGitRepo':
await this.loadGitRepo(data.repoId);
break;
case 'syncGitRepo':
await this.syncGitRepo(data.repoId);
break;
case 'deleteGitRepo':
await this.deleteGitRepo(data.repoId);
break;
case 'importGitFile':
await this.importGitFile(data.filePath);
break;
}
});
}
// === Git 仓库管理方法 ===
/**
* 加载 Git 仓库数据
*/
async loadGitRepos() {
try {
const globalStoragePath = this.extensionUri.fsPath;
const reposFile = path.join(globalStoragePath, 'git-repos.json');
if (fs.existsSync(reposFile)) {
const data = await fs.promises.readFile(reposFile, 'utf8');
this.gitRepos = JSON.parse(data);
}
}
catch (error) {
vscode.window.showErrorMessage(`加载 Git 仓库数据失败: ${error}`);
}
}
/**
* 保存 Git 仓库数据
*/
async saveGitRepos() {
try {
const globalStoragePath = this.extensionUri.fsPath;
const reposFile = path.join(globalStoragePath, 'git-repos.json');
// 确保目录存在
await fs.promises.mkdir(path.dirname(reposFile), { recursive: true });
await fs.promises.writeFile(reposFile, JSON.stringify(this.gitRepos, null, 2));
}
catch (error) {
vscode.window.showErrorMessage(`保存 Git 仓库数据失败: ${error}`);
}
}
/**
* 添加 Git 仓库到配置目录
*/
async addGitRepo(url, name, branch) {
try {
// 验证 URL
if (!url || !url.startsWith('http')) {
vscode.window.showErrorMessage('请输入有效的 Git 仓库 URL');
return;
}
const repoId = 'git-' + Date.now();
// 构建本地路径
let localPath = '';
if (this.currentContainerId && this.currentProjectId) {
const projectPath = this.projectPaths.get(this.currentProjectId);
const container = this.containers.find(c => c.id === this.currentContainerId);
const aircraft = this.aircrafts.find(a => a.id === container?.aircraftId);
if (projectPath && container && aircraft) {
localPath = path.join(projectPath, aircraft.name, container.name, name);
console.log(`📁 Git仓库将保存到容器目录: ${localPath}`);
}
}
if (!localPath) {
localPath = path.join(this.extensionUri.fsPath, name);
console.log(`📁 Git仓库将保存到扩展目录: ${localPath}`);
}
// 修改:检查目标目录是否已存在
if (fs.existsSync(localPath)) {
vscode.window.showErrorMessage(`目标目录已存在: ${localPath},请选择不同的名称或删除现有目录`);
return;
}
// 修改:放宽重复检查,只检查完全相同的路径
const existingRepo = this.gitRepos.find(repo => repo.localPath === localPath // 只检查路径完全相同的情况
);
if (existingRepo) {
vscode.window.showWarningMessage('该路径已存在 Git 仓库');
return;
}
const newRepo = {
id: repoId,
name: name,
url: url,
localPath: localPath,
branch: branch || 'main',
lastSync: new Date().toLocaleString()
};
console.log(`📁 准备克隆仓库: ${name}, 分支: ${newRepo.branch}, 路径: ${localPath}`);
// 显示进度
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在克隆仓库: ${name} (${newRepo.branch})`,
cancellable: false
}, async (progress) => {
progress.report({ increment: 0 });
try {
// 确保目录存在
await fs.promises.mkdir(path.dirname(localPath), { recursive: true });
// 克隆仓库
await isomorphic_git_1.default.clone({
fs: fs,
http: node_1.default,
dir: localPath,
url: url,
singleBranch: true,
depth: 1,
ref: branch || 'main',
onProgress: (event) => {
if (event.total) {
const percent = (event.loaded / event.total) * 100;
progress.report({ increment: percent, message: `${event.phase}...` });
}
}
});
console.log('✅ Git克隆成功完成');
this.gitRepos.push(newRepo);
await this.saveGitRepos();
console.log('✅ 仓库数据保存成功');
vscode.window.showInformationMessage(`Git 仓库克隆成功: ${name} (${newRepo.branch})`);
console.log('🌳 开始加载仓库文件树...');
// 自动加载仓库文件树
this.currentRepoId = repoId;
await this.loadGitRepoFileTree(repoId);
console.log('✅ 仓库文件树加载完成');
// 更新 Webview 显示
this.updateWebview();
}
catch (error) {
console.error('❌ 在克隆过程中捕获错误:', error);
vscode.window.showErrorMessage(`克隆仓库失败: ${error}`);
// 清理失败的克隆目录
try {
console.log('🧹 开始清理失败的克隆目录...');
await fs.promises.rm(localPath, { recursive: true, force: true });
console.log('✅ 失败目录清理完成');
}
catch (cleanupError) {
console.error('❌ 清理失败目录时出错:', cleanupError);
}
}
});
}
catch (error) {
console.error('❌ 在addGitRepo外部捕获错误:', error);
vscode.window.showErrorMessage(`添加 Git 仓库失败: ${error}`);
}
}
/**
* 加载 Git 仓库文件树
*/
async loadGitRepo(repoId) {
this.currentRepoId = repoId;
await this.loadGitRepoFileTree(repoId);
this.updateWebview();
}
/**
* 同步 Git 仓库
*/
async syncGitRepo(repoId) {
const repo = this.gitRepos.find(r => r.id === repoId);
if (!repo) {
vscode.window.showErrorMessage('未找到指定的 Git 仓库');
return;
}
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在同步仓库: ${repo.name}`,
cancellable: false
}, async (progress) => {
try {
progress.report({ increment: 0, message: '拉取最新更改...' });
// 拉取最新更改
await isomorphic_git_1.default.pull({
fs: fs,
http: node_1.default,
dir: repo.localPath,
author: { name: 'DCSP User', email: 'user@dcsp.local' },
fastForward: true
});
// 更新最后同步时间
repo.lastSync = new Date().toLocaleString();
await this.saveGitRepos();
// 重新加载文件树
await this.loadGitRepoFileTree(repoId);
vscode.window.showInformationMessage(`Git 仓库同步成功: ${repo.name}`);
this.updateWebview();
}
catch (error) {
vscode.window.showErrorMessage(`同步 Git 仓库失败: ${error}`);
}
});
}
/**
* 删除 Git 仓库
*/
async deleteGitRepo(repoId) {
const repo = this.gitRepos.find(r => r.id === repoId);
if (!repo)
return;
const confirm = await vscode.window.showWarningMessage(`确定要删除 Git 仓库 "${repo.name}" 吗?这也会删除本地副本。`, { modal: true }, '确定删除');
if (confirm === '确定删除') {
try {
// 删除本地目录
await fs.promises.rm(repo.localPath, { recursive: true, force: true });
// 从列表中移除
this.gitRepos = this.gitRepos.filter(r => r.id !== repoId);
await this.saveGitRepos();
// 如果删除的是当前仓库,清空状态
if (this.currentRepoId === repoId) {
this.currentRepoId = '';
this.currentRepoFileTree = [];
}
vscode.window.showInformationMessage(`Git 仓库已删除: ${repo.name}`);
this.updateWebview();
}
catch (error) {
vscode.window.showErrorMessage(`删除 Git 仓库失败: ${error}`);
}
}
}
/**
* 加载 Git 仓库文件树
*/
async loadGitRepoFileTree(repoId) {
const repo = this.gitRepos.find(r => r.id === repoId);
if (!repo)
return;
// 通知前端开始加载
this.panel.webview.postMessage({
type: 'gitRepoLoading',
loading: true
});
try {
const fileTree = await this.buildFileTree(repo.localPath);
this.currentRepoFileTree = fileTree;
// 更新最后访问时间
repo.lastSync = new Date().toLocaleString();
await this.saveGitRepos();
}
catch (error) {
vscode.window.showErrorMessage(`加载仓库文件树失败: ${error}`);
this.currentRepoFileTree = [];
}
// 通知前端加载完成
this.panel.webview.postMessage({
type: 'gitRepoLoading',
loading: false
});
this.updateWebview();
}
/**
* 构建文件树
*/
async buildFileTree(dir, relativePath = '') {
try {
const files = await fs.promises.readdir(dir);
const tree = [];
for (const file of files) {
// 忽略 .git 文件夹和其他隐藏文件
if (file.startsWith('.'))
continue;
const filePath = path.join(dir, file);
const stats = await fs.promises.stat(filePath);
const currentRelativePath = path.join(relativePath, file);
if (stats.isDirectory()) {
const children = await this.buildFileTree(filePath, currentRelativePath);
tree.push({
name: file,
type: 'folder',
path: currentRelativePath,
children: children
});
}
else {
tree.push({
name: file,
type: 'file',
path: currentRelativePath
});
}
}
return tree;
}
catch (error) {
console.error('构建文件树失败:', error);
return [];
}
}
/**
* 导入 Git 文件到当前容器
*/
async importGitFile(filePath) {
if (!this.currentRepoId || !this.currentContainerId) {
vscode.window.showErrorMessage('请先选择 Git 仓库和容器');
return;
}
const repo = this.gitRepos.find(r => r.id === this.currentRepoId);
if (!repo) {
vscode.window.showErrorMessage('未找到当前 Git 仓库');
return;
}
const container = this.containers.find(c => c.id === this.currentContainerId);
if (!container) {
vscode.window.showErrorMessage('未找到当前容器');
return;
}
try {
const fullPath = path.join(repo.localPath, filePath);
const content = await fs.promises.readFile(fullPath, 'utf8');
const fileName = path.basename(filePath);
// 创建新配置
const newId = 'cfg' + (this.configs.length + 1);
const newConfig = {
id: newId,
name: fileName,
fileName: fileName,
content: content,
containerId: this.currentContainerId
};
this.configs.push(newConfig);
await this.saveCurrentProjectData();
vscode.window.showInformationMessage(`文件已导入到容器 ${container.name}: ${fileName}`);
this.updateWebview();
}
catch (error) {
vscode.window.showErrorMessage(`导入文件失败: ${error}`);
}
}
// === 原有项目配置管理方法 ===
// === 打开现有项目功能 ===
async openExistingProject() {
try {
@@ -172,16 +555,12 @@ class ConfigPanel {
*/
async saveCurrentProjectData() {
try {
console.log('开始保存当前项目数据...');
console.log('当前项目ID:', this.currentProjectId);
if (!this.currentProjectId) {
console.log('未找到当前项目ID跳过保存数据');
vscode.window.showWarningMessage('未找到当前项目,数据将不会保存');
return;
}
const projectPath = this.projectPaths.get(this.currentProjectId);
if (!projectPath) {
console.log('未找到项目路径,跳过保存数据');
vscode.window.showWarningMessage('未找到项目存储路径,数据将不会保存');
return;
}
@@ -198,18 +577,11 @@ class ConfigPanel {
containers: currentProjectContainers,
configs: currentProjectConfigs
};
console.log('要保存的当前项目数据:', {
projects: data.projects.length,
aircrafts: data.aircrafts.length,
containers: data.containers.length,
configs: data.configs.length
});
const uint8Array = new TextEncoder().encode(JSON.stringify(data, null, 2));
await vscode.workspace.fs.writeFile(dataUri, uint8Array);
console.log('当前项目数据已保存到:', dataUri.fsPath);
console.log('当前项目数据已保存');
}
catch (error) {
console.error('保存当前项目数据时出错:', error);
vscode.window.showErrorMessage(`保存项目数据失败: ${error}`);
}
}
@@ -231,7 +603,6 @@ class ConfigPanel {
const fileData = await vscode.workspace.fs.readFile(dataUri);
const dataStr = new TextDecoder().decode(fileData);
const data = JSON.parse(dataStr);
console.log('从文件加载的数据:', data);
// 清空现有数据
this.projects = [];
this.aircrafts = [];
@@ -250,12 +621,6 @@ class ConfigPanel {
if (data.configs && Array.isArray(data.configs)) {
this.configs = data.configs;
}
console.log('加载后的数据状态:', {
projects: this.projects.length,
aircrafts: this.aircrafts.length,
containers: this.containers.length,
configs: this.configs.length
});
// 设置当前项目为第一个项目(如果有的话)
if (this.projects.length > 0) {
this.currentProjectId = this.projects[0].id;
@@ -267,7 +632,6 @@ class ConfigPanel {
return true;
}
catch (error) {
console.error('加载项目数据时出错:', error);
vscode.window.showErrorMessage(`加载项目数据失败: ${error}`);
return false;
}
@@ -474,7 +838,6 @@ class ConfigPanel {
}
// 创建新容器
async createContainer(name) {
console.log('创建容器当前飞行器ID:', this.currentAircraftId);
if (!this.currentAircraftId) {
vscode.window.showErrorMessage('无法创建容器:未找到当前飞行器');
return;
@@ -504,10 +867,6 @@ class ConfigPanel {
content: `# ${name} 的 Docker Compose 配置\nversion: '3.8'\n\nservices:\n ${name.toLowerCase().replace(/\\s+/g, '-')}:\n build: .\n container_name: ${name}\n ports:\n - "8080:8080"\n environment:\n - NODE_ENV=production\n volumes:\n - ./data:/app/data\n restart: unless-stopped`,
containerId: newId
});
console.log('创建容器后的数据状态:', {
containers: this.containers.length,
configs: this.configs.length
});
vscode.window.showInformationMessage(`新建容器: ${name} (包含2个默认配置文件)`);
await this.saveCurrentProjectData();
this.updateWebview();
@@ -645,6 +1004,109 @@ class ConfigPanel {
});
}
}
// === Git 分支管理 ===
async fetchBranches(url) {
try {
console.log('🌿 开始获取分支列表:', url);
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: '正在获取分支信息',
cancellable: false
}, async (progress) => {
progress.report({ increment: 0, message: '连接远程仓库...' });
try {
// 使用 isomorphic-git 的 listServerRefs
progress.report({ increment: 30, message: '获取远程引用...' });
console.log('🔍 使用 listServerRefs 获取分支信息...');
const refs = await isomorphic_git_1.default.listServerRefs({
http: node_1.default,
url: url
});
console.log('📋 获取到的引用:', refs);
// 过滤出分支引用 (refs/heads/ 和 refs/remotes/origin/)
const branchRefs = refs.filter(ref => ref.ref.startsWith('refs/heads/') || ref.ref.startsWith('refs/remotes/origin/'));
console.log('🌿 过滤后的分支引用:', branchRefs);
// 构建分支数据
const branches = branchRefs.map(ref => {
const isRemote = ref.ref.startsWith('refs/remotes/');
const branchName = isRemote
? ref.ref.replace('refs/remotes/origin/', '')
: ref.ref.replace('refs/heads/', '');
return {
name: branchName,
isCurrent: branchName === 'main' || branchName === 'master',
isRemote: isRemote,
selected: branchName === 'main' || branchName === 'master'
};
});
console.log('🎯 最终分支列表:', branches);
if (branches.length === 0) {
throw new Error('未找到任何分支');
}
progress.report({ increment: 80, message: '处理分支数据...' });
// 发送分支数据到前端
this.panel.webview.postMessage({
type: 'branchesFetched',
branches: branches,
repoUrl: url
});
progress.report({ increment: 100, message: '完成' });
}
catch (error) {
console.error('❌ 使用 listServerRefs 获取分支失败:', error);
// 如果方法失败,使用模拟数据
console.log('🔄 使用模拟分支数据');
const mockBranches = [
{ name: 'main', isCurrent: true, isRemote: false, selected: true },
{ name: 'master', isCurrent: false, isRemote: false, selected: false },
{ name: 'develop', isCurrent: false, isRemote: false, selected: false },
{ name: 'feature/new-feature', isCurrent: false, isRemote: false, selected: false }
];
this.panel.webview.postMessage({
type: 'branchesFetched',
branches: mockBranches,
repoUrl: url
});
vscode.window.showWarningMessage('使用模拟分支数据,实际分支可能不同');
}
});
}
catch (error) {
console.error('❌ 获取分支失败:', error);
vscode.window.showErrorMessage(`获取分支失败: ${error}`);
}
}
async cloneBranches(url, branches) {
try {
console.log('🚀 开始克隆分支:', { url, branches });
// 显示总进度
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在克隆 ${branches.length} 个分支`,
cancellable: false
}, async (progress) => {
for (let i = 0; i < branches.length; i++) {
const branch = branches[i];
const progressPercent = (i / branches.length) * 100;
progress.report({
increment: progressPercent,
message: `克隆分支: ${branch} (${i + 1}/${branches.length})`
});
console.log(`📥 克隆分支: ${branch}`);
await this.addGitRepo(url, this.generateRepoName(url, branch), branch);
}
});
vscode.window.showInformationMessage(`成功克隆 ${branches.length} 个分支`);
}
catch (error) {
console.error('❌ 克隆分支失败:', error);
vscode.window.showErrorMessage(`克隆分支失败: ${error}`);
}
}
generateRepoName(url, branch) {
const repoName = url.split('/').pop()?.replace('.git', '') || 'unknown-repo';
return `${repoName}-${branch.replace(/\//g, '-')}`;
}
// 更新视图
updateWebview() {
this.panel.webview.html = this.getWebviewContent();
@@ -673,9 +1135,14 @@ class ConfigPanel {
case 'configs':
const currentContainer = this.containers.find(c => c.id === this.currentContainerId);
const containerConfigs = this.configs.filter(cfg => cfg.containerId === this.currentContainerId);
const currentRepo = this.gitRepos.find(r => r.id === this.currentRepoId);
return this.configView.render({
container: currentContainer,
configs: containerConfigs
configs: containerConfigs,
gitRepos: this.gitRepos,
currentGitRepo: currentRepo,
gitFileTree: this.currentRepoFileTree,
gitLoading: false
});
default:
return this.projectView.render({

File diff suppressed because one or more lines are too long

View File

@@ -7,7 +7,13 @@ class ConfigView extends BaseView_1.BaseView {
render(data) {
const container = data?.container;
const configs = data?.configs || [];
// 生成配置列表的 HTML - 移除文件名编辑功能
const gitRepos = data?.gitRepos || [];
const currentGitRepo = data?.currentGitRepo;
const gitFileTree = data?.gitFileTree || [];
const gitLoading = data?.gitLoading || false;
const gitBranches = data?.gitBranches || [];
const gitRepoUrl = data?.gitRepoUrl || '';
// 生成配置列表的 HTML
const configsHtml = configs.map((config) => `
<tr>
<td>
@@ -21,6 +27,31 @@ class ConfigView extends BaseView_1.BaseView {
</td>
</tr>
`).join('');
// 生成 Git 仓库列表的 HTML
const gitReposHtml = gitRepos.map(repo => `
<tr>
<td>
<span class="repo-name" data-repo-id="${repo.id}">📁 ${repo.name}</span>
<div style="font-size: 12px; color: var(--vscode-descriptionForeground); margin-top: 4px;">
${repo.url}
</div>
<div style="font-size: 11px; color: var(--vscode-descriptionForeground);">
分支: ${repo.branch} | 最后同步: ${repo.lastSync}
</div>
</td>
<td>
<span class="clickable" onclick="loadGitRepo('${repo.id}')">打开</span>
<span class="clickable" onclick="syncGitRepo('${repo.id}')" style="margin-left: 10px;">同步</span>
</td>
<td>
<button class="btn-delete" onclick="deleteGitRepo('${repo.id}')">删除</button>
</td>
</tr>
`).join('');
// 生成分支选择的 HTML
const branchesHtml = gitBranches.length > 0 ? this.generateBranchesHtml(gitBranches) : '';
// 生成文件树的 HTML
const fileTreeHtml = gitFileTree.length > 0 ? this.renderFileTree(gitFileTree) : '<div style="text-align: center; padding: 20px; color: var(--vscode-descriptionForeground);">选择仓库以浏览文件</div>';
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
@@ -28,6 +59,104 @@ class ConfigView extends BaseView_1.BaseView {
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>配置管理</title>
${this.getStyles()}
<style>
.git-container {
display: flex;
gap: 20px;
margin-top: 20px;
}
.repo-list {
flex: 1;
min-width: 300px;
}
.file-tree {
flex: 2;
min-width: 400px;
border: 1px solid var(--vscode-panel-border);
border-radius: 4px;
padding: 15px;
background: var(--vscode-panel-background);
max-height: 400px;
overflow-y: auto;
}
.tree-item {
margin: 2px 0;
}
.tree-folder {
cursor: pointer;
padding: 2px 4px;
border-radius: 2px;
display: inline-block;
}
.tree-folder:hover {
background: var(--vscode-list-hoverBackground);
}
.tree-file {
padding: 2px 4px;
border-radius: 2px;
display: inline-block;
}
.tree-file:hover {
background: var(--vscode-list-hoverBackground);
}
.tree-children {
margin-left: 10px;
}
.current-repo {
background: var(--vscode-badge-background);
padding: 10px;
border-radius: 4px;
margin-bottom: 15px;
}
.loading {
text-align: center;
padding: 20px;
color: var(--vscode-descriptionForeground);
}
.btn-sync {
background: var(--vscode-button-background);
color: var(--vscode-button-foreground);
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
margin-left: 10px;
}
.btn-sync:hover {
background: var(--vscode-button-hoverBackground);
}
.branch-selection {
border: 1px solid var(--vscode-input-border);
}
.branch-item:hover {
background: var(--vscode-list-hoverBackground);
}
.url-input-section {
background: var(--vscode-panel-background);
padding: 15px;
border-radius: 4px;
margin-bottom: 15px;
border: 1px solid var(--vscode-input-border);
}
.debug-panel {
background: var(--vscode-inputValidation-infoBackground);
padding: 10px;
margin-bottom: 15px;
border-radius: 4px;
border: 1px solid var(--vscode-inputValidation-infoBorder);
}
.debug-info {
font-size: 12px;
color: var(--vscode-input-foreground);
font-family: 'Courier New', monospace;
}
.section-title {
margin: 30px 0 15px 0;
padding-bottom: 10px;
border-bottom: 2px solid var(--vscode-panel-border);
color: var(--vscode-titleBar-activeForeground);
}
</style>
</head>
<body>
<div class="header">
@@ -35,6 +164,8 @@ class ConfigView extends BaseView_1.BaseView {
<button class="back-btn" onclick="goBackToContainers()">← 返回容器管理</button>
</div>
<!-- 配置管理部分 -->
<h3 class="section-title">📋 配置文件管理</h3>
<table class="table">
<thead>
<tr>
@@ -53,6 +184,55 @@ class ConfigView extends BaseView_1.BaseView {
</tbody>
</table>
<!-- Git 仓库管理部分 -->
<h3 class="section-title">📚 Git 仓库管理</h3>
<!-- URL 输入区域 -->
<div class="url-input-section">
<h4>🔗 添加 Git 仓库</h4>
<div style="display: flex; gap: 10px; margin-top: 10px;">
<input type="text" id="repoUrlInput"
placeholder="请输入 Git 仓库 URL例如: https://github.com/username/repo.git"
value="${gitRepoUrl}"
style="flex: 1; padding: 8px; background: var(--vscode-input-background); color: var(--vscode-input-foreground); border: 1px solid var(--vscode-input-border); border-radius: 4px;">
<button class="btn-new" onclick="fetchBranches()">获取分支</button>
</div>
<div id="branchSelectionContainer">
${branchesHtml}
</div>
</div>
<div style="margin-bottom: 20px;">
${currentGitRepo ? `
<div class="current-repo">
<strong>当前仓库:</strong> ${currentGitRepo.name} (${currentGitRepo.url})
<button class="btn-sync" onclick="syncGitRepo('${currentGitRepo.id}')">同步</button>
</div>
` : ''}
</div>
<div class="git-container">
<div class="repo-list">
<table class="table">
<thead>
<tr>
<th width="60%">仓库</th>
<th width="20%">操作</th>
<th width="20%">管理</th>
</tr>
</thead>
<tbody>
${gitReposHtml}
</tbody>
</table>
</div>
<div class="file-tree">
<h4>📂 文件浏览器</h4>
${gitLoading ? '<div class="loading">🔄 加载中...</div>' : fileTreeHtml}
</div>
</div>
<!-- 配置文件编辑器 -->
<div class="config-editor" id="configEditor" style="display: none;">
<h3>📝 编辑配置文件</h3>
@@ -66,7 +246,10 @@ class ConfigView extends BaseView_1.BaseView {
<script>
const vscode = acquireVsCodeApi();
let currentConfigId = null;
let selectedBranches = new Set();
let currentRepoUrl = '';
// 配置管理功能
function editConfigName(configId, currentName) {
showPromptDialog(
'修改配置名称',
@@ -145,6 +328,168 @@ class ConfigView extends BaseView_1.BaseView {
vscode.postMessage({ type: 'goBackToContainers' });
}
// Git 仓库管理功能
function updateDebugInfo(message) {
const debugElement = document.getElementById('debugInfo');
if (debugElement) {
debugElement.innerHTML = message;
console.log('🔍 调试信息:', message);
}
}
function fetchBranches() {
const urlInput = document.getElementById('repoUrlInput');
const repoUrl = urlInput.value.trim();
if (!repoUrl) {
alert('请输入 Git 仓库 URL');
return;
}
if (!repoUrl.startsWith('http')) {
alert('请输入有效的 Git 仓库 URL');
return;
}
currentRepoUrl = repoUrl;
console.log('🌿 获取分支列表:', repoUrl);
updateDebugInfo('🌿 正在获取分支列表...');
vscode.postMessage({
type: 'fetchBranches',
url: repoUrl
});
}
function toggleBranch(branchName) {
const checkbox = document.getElementById('branch-' + branchName.replace(/[^a-zA-Z0-9]/g, '-'));
if (checkbox.checked) {
selectedBranches.add(branchName);
} else {
selectedBranches.delete(branchName);
}
console.log('选中的分支:', Array.from(selectedBranches));
updateDebugInfo('选中的分支: ' + Array.from(selectedBranches).join(', '));
}
function cloneSelectedBranches() {
if (selectedBranches.size === 0) {
alert('请至少选择一个分支');
return;
}
console.log('🚀 开始克隆选中的分支:', Array.from(selectedBranches));
updateDebugInfo('🚀 开始克隆分支: ' + Array.from(selectedBranches).join(', '));
vscode.postMessage({
type: 'cloneBranches',
url: currentRepoUrl,
branches: Array.from(selectedBranches)
});
// 重置选择
selectedBranches.clear();
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => checkbox.checked = false);
// 隐藏分支选择区域
document.getElementById('branchSelectionContainer').innerHTML = '';
updateDebugInfo('✅ 分支克隆请求已发送');
}
function cancelBranchSelection() {
selectedBranches.clear();
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => checkbox.checked = false);
// 隐藏分支选择区域
document.getElementById('branchSelectionContainer').innerHTML = '';
updateDebugInfo('❌ 已取消分支选择');
vscode.postMessage({
type: 'cancelBranchSelection'
});
}
function loadGitRepo(repoId) {
console.log('📂 加载仓库:', repoId);
updateDebugInfo('📂 正在加载仓库...');
vscode.postMessage({
type: 'loadGitRepo',
repoId: repoId
});
}
function syncGitRepo(repoId) {
console.log('🔄 同步仓库:', repoId);
updateDebugInfo('🔄 正在同步仓库...');
vscode.postMessage({
type: 'syncGitRepo',
repoId: repoId
});
}
function deleteGitRepo(repoId) {
if (confirm('确定删除这个 Git 仓库吗?')) {
console.log('🗑️ 删除仓库:', repoId);
updateDebugInfo('🗑️ 正在删除仓库...');
vscode.postMessage({
type: 'deleteGitRepo',
repoId: repoId
});
}
}
function importFile(filePath) {
if (confirm('确定要将此文件导入到当前容器吗?')) {
console.log('📥 导入文件:', filePath);
updateDebugInfo('📥 正在导入文件...');
vscode.postMessage({
type: 'importGitFile',
filePath: filePath
});
}
}
function toggleFolder(folderPath) {
const folderElement = document.getElementById('folder-' + folderPath.replace(/[^a-zA-Z0-9]/g, '-'));
if (folderElement) {
folderElement.style.display = folderElement.style.display === 'none' ? 'block' : 'none';
}
}
// 动态渲染分支选择区域
function renderBranchSelection(branches, repoUrl) {
const container = document.getElementById('branchSelectionContainer');
if (branches.length === 0) {
container.innerHTML = '<div style="text-align: center; padding: 10px; color: var(--vscode-descriptionForeground);">未找到分支</div>';
return;
}
let branchesHtml = '<div class="branch-selection" style="margin: 15px 0; padding: 15px; background: var(--vscode-panel-background); border-radius: 4px;">';
branchesHtml += '<h4>🌿 选择要克隆的分支 (共 ' + branches.length + ' 个)</h4>';
branchesHtml += '<div style="max-height: 200px; overflow-y: auto; margin: 10px 0;">';
branches.forEach(branch => {
branchesHtml += '<div class="branch-item" style="padding: 8px; border-bottom: 1px solid var(--vscode-panel-border); display: flex; align-items: center;">';
branchesHtml += '<input type="checkbox" id="branch-' + branch.name.replace(/[^a-zA-Z0-9]/g, '-') + '" ';
branchesHtml += (branch.selected ? 'checked' : '') + ' onchange="toggleBranch(\\'' + branch.name + '\\')" style="margin-right: 10px;">';
branchesHtml += '<label for="branch-' + branch.name.replace(/[^a-zA-Z0-9]/g, '-') + '" style="flex: 1; cursor: pointer;">';
branchesHtml += (branch.isCurrent ? '⭐ ' : '') + branch.name;
branchesHtml += (branch.isRemote ? '(远程)' : '(本地)') + '</label></div>';
});
branchesHtml += '</div>';
branchesHtml += '<div style="margin-top: 15px;">';
branchesHtml += '<button class="btn-new" onclick="cloneSelectedBranches()" style="margin-right: 10px;">✅ 克隆选中分支</button>';
branchesHtml += '<button class="back-btn" onclick="cancelBranchSelection()">取消</button>';
branchesHtml += '</div></div>';
container.innerHTML = branchesHtml;
}
// 对话框函数
function showConfirmDialog(title, message, onConfirm, onCancel) {
const overlay = document.createElement('div');
@@ -225,18 +570,89 @@ class ConfigView extends BaseView_1.BaseView {
delete window.promptCallback;
}
// 消息监听
window.addEventListener('message', event => {
const message = event.data;
console.log('📨 前端收到后端消息:', message);
if (message.type === 'branchesFetched') {
console.log('🌿 收到分支数据:', message.branches);
updateDebugInfo('✅ 获取到 ' + message.branches.length + ' 个分支');
renderBranchSelection(message.branches, message.repoUrl);
}
if (message.type === 'configFileLoaded') {
document.getElementById('configContent').value = message.content;
}
if (message.type === 'gitRepoLoading') {
updateDebugInfo(message.loading ? '🔄 后端正在加载仓库文件树...' : '✅ 后端文件树加载完成');
}
});
// 移除原来的复杂点击事件处理,现在文件名直接调用 openConfigFile
// 初始化
document.addEventListener('DOMContentLoaded', function() {
console.log('📄 ConfigView 页面加载完成');
updateDebugInfo('📄 页面加载完成 - 等待用户操作');
setTimeout(() => {
document.querySelectorAll('.tree-children').forEach(el => {
el.style.display = 'block';
});
}, 100);
});
</script>
</body>
</html>`;
}
generateBranchesHtml(branches) {
if (branches.length === 0)
return '';
let html = '<div class="branch-selection" style="margin: 15px 0; padding: 15px; background: var(--vscode-panel-background); border-radius: 4px;">';
html += '<h4>🌿 选择要克隆的分支 (共 ' + branches.length + ' 个)</h4>';
html += '<div style="max-height: 200px; overflow-y: auto; margin: 10px 0;">';
branches.forEach(branch => {
const branchId = 'branch-' + branch.name.replace(/[^a-zA-Z0-9]/g, '-');
html += '<div class="branch-item" style="padding: 8px; border-bottom: 1px solid var(--vscode-panel-border); display: flex; align-items: center;">';
html += '<input type="checkbox" id="' + branchId + '" ';
html += (branch.selected ? 'checked' : '') + ' onchange="toggleBranch(\'' + branch.name + '\')" style="margin-right: 10px;">';
html += '<label for="' + branchId + '" style="flex: 1; cursor: pointer;">';
html += (branch.isCurrent ? '⭐ ' : '') + branch.name;
html += (branch.isRemote ? '(远程)' : '(本地)') + '</label></div>';
});
html += '</div>';
html += '<div style="margin-top: 15px;">';
html += '<button class="btn-new" onclick="cloneSelectedBranches()" style="margin-right: 10px;">✅ 克隆选中分支</button>';
html += '<button class="back-btn" onclick="cancelBranchSelection()">取消</button>';
html += '</div></div>';
return html;
}
renderFileTree(nodes, level = 0) {
return nodes.map(node => {
const paddingLeft = level * 20;
if (node.type === 'folder') {
return `
<div class="tree-item" style="padding-left: ${paddingLeft}px;">
<span class="tree-folder" onclick="toggleFolder('${node.path}')">
📁 ${node.name}
</span>
<div id="folder-${node.path.replace(/[^a-zA-Z0-9]/g, '-')}" class="tree-children">
${this.renderFileTree(node.children || [], level + 1)}
</div>
</div>
`;
}
else {
return `
<div class="tree-item" style="padding-left: ${paddingLeft}px;">
<span class="tree-file clickable" onclick="importFile('${node.path}')">
📄 ${node.name}
</span>
</div>
`;
}
}).join('');
}
}
exports.ConfigView = ConfigView;
//# sourceMappingURL=ConfigView.js.map

View File

@@ -1 +1 @@
{"version":3,"file":"ConfigView.js","sourceRoot":"","sources":["../../../src/panels/views/ConfigView.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AACjC,yCAAsC;AAGtC,MAAa,UAAW,SAAQ,mBAAQ;IACpC,MAAM,CAAC,IAA0B;QAC7B,MAAM,SAAS,GAAG,IAAI,EAAE,SAAS,CAAC;QAClC,MAAM,OAAO,GAAG,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC;QAEpC,2BAA2B;QAC3B,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,MAAsB,EAAE,EAAE,CAAC;;;sEAGE,MAAM,CAAC,EAAE,OAAO,MAAM,CAAC,IAAI,UAAU,MAAM,CAAC,IAAI;;;uEAG/C,MAAM,CAAC,EAAE,UAAU,MAAM,CAAC,QAAQ;;;wEAGjC,MAAM,CAAC,EAAE;;;SAGxE,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAEZ,OAAO;;;;;;MAMT,IAAI,CAAC,SAAS,EAAE;;;;gFAI0D,SAAS,EAAE,IAAI,IAAI,MAAM;;;;;;;;;;;;;cAa3F,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AM,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,gBAAgB,CAAC;QACnE,CAAC,CAAC,CAAC;QAEH,IAAI,IAAI,QAAQ,CAAC;QACjB,IAAI,IAAI,iCAAiC,CAAC;QAC1C,IAAI,IAAI,yGAAyG,CAAC;QAClH,IAAI,IAAI,wEAAwE,CAAC;QACjF,IAAI,IAAI,cAAc,CAAC;QAEvB,OAAO,IAAI,CAAC;IAChB,CAAC;IAEO,cAAc,CAAC,KAAoB,EAAE,KAAK,GAAG,CAAC;QAClD,OAAO,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;YACpB,MAAM,WAAW,GAAG,KAAK,GAAG,EAAE,CAAC;YAC/B,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACxB,OAAO;kEAC2C,WAAW;2EACF,IAAI,CAAC,IAAI;iCACnD,IAAI,CAAC,IAAI;;0CAEA,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC;8BACnD,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,EAAE,KAAK,GAAG,CAAC,CAAC;;;iBAGhE,CAAC;aACL;iBAAM;gBACH,OAAO;kEAC2C,WAAW;iFACI,IAAI,CAAC,IAAI;iCACzD,IAAI,CAAC,IAAI;;;iBAGzB,CAAC;aACL;QACL,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAChB,CAAC;CACJ;AA1pBD,gCA0pBC"}

470
out/panels/views/GitView.js Normal file
View File

@@ -0,0 +1,470 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitView = void 0;
// src/panels/views/GitView.ts
const BaseView_1 = require("./BaseView");
class GitView extends BaseView_1.BaseView {
render(data) {
const repos = data?.repos || [];
const currentRepo = data?.currentRepo;
const fileTree = data?.fileTree || [];
const loading = data?.loading || false;
const branches = data?.branches || [];
const repoUrl = data?.repoUrl || '';
// 生成仓库列表的 HTML
const reposHtml = repos.map(repo => `
<tr>
<td>
<span class="repo-name" data-repo-id="${repo.id}">📁 ${repo.name}</span>
<div style="font-size: 12px; color: var(--vscode-descriptionForeground); margin-top: 4px;">
${repo.url}
</div>
<div style="font-size: 11px; color: var(--vscode-descriptionForeground);">
分支: ${repo.branch} | 最后同步: ${repo.lastSync}
</div>
</td>
<td>
<span class="clickable" onclick="loadRepo('${repo.id}')">打开</span>
<span class="clickable" onclick="syncRepo('${repo.id}')" style="margin-left: 10px;">同步</span>
</td>
<td>
<button class="btn-delete" onclick="deleteRepo('${repo.id}')">删除</button>
</td>
</tr>
`).join('');
// 生成分支选择的 HTML - 使用转义符处理嵌套
const branchesHtml = branches.length > 0 ? this.generateBranchesHtml(branches) : '';
// 生成文件树的 HTML
const fileTreeHtml = fileTree.length > 0 ? this.renderFileTree(fileTree) : '<div style="text-align: center; padding: 20px; color: var(--vscode-descriptionForeground);">选择仓库以浏览文件</div>';
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Git 仓库管理</title>
${this.getStyles()}
<style>
.git-container {
display: flex;
gap: 20px;
margin-top: 20px;
}
.repo-list {
flex: 1;
min-width: 300px;
}
.file-tree {
flex: 2;
min-width: 400px;
border: 1px solid var(--vscode-panel-border);
border-radius: 4px;
padding: 15px;
background: var(--vscode-panel-background);
max-height: 600px;
overflow-y: auto;
}
.tree-item {
margin: 2px 0;
}
.tree-folder {
cursor: pointer;
padding: 2px 4px;
border-radius: 2px;
display: inline-block;
}
.tree-folder:hover {
background: var(--vscode-list-hoverBackground);
}
.tree-file {
padding: 2px 4px;
border-radius: 2px;
display: inline-block;
}
.tree-file:hover {
background: var(--vscode-list-hoverBackground);
}
.tree-children {
margin-left: 10px;
}
.current-repo {
background: var(--vscode-badge-background);
padding: 10px;
border-radius: 4px;
margin-bottom: 15px;
}
.loading {
text-align: center;
padding: 20px;
color: var(--vscode-descriptionForeground);
}
.btn-sync {
background: var(--vscode-button-background);
color: var(--vscode-button-foreground);
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
margin-left: 10px;
}
.btn-sync:hover {
background: var(--vscode-button-hoverBackground);
}
.branch-selection {
border: 1px solid var(--vscode-input-border);
}
.branch-item:hover {
background: var(--vscode-list-hoverBackground);
}
.url-input-section {
background: var(--vscode-panel-background);
padding: 15px;
border-radius: 4px;
margin-bottom: 15px;
border: 1px solid var(--vscode-input-border);
}
.debug-panel {
background: var(--vscode-inputValidation-infoBackground);
padding: 10px;
margin-bottom: 15px;
border-radius: 4px;
border: 1px solid var(--vscode-inputValidation-infoBorder);
}
.debug-info {
font-size: 12px;
color: var(--vscode-input-foreground);
font-family: 'Courier New', monospace;
}
</style>
</head>
<body>
<div class="header">
<h2>📚 Git 仓库管理</h2>
<button class="back-btn" onclick="goBackToProjects()">← 返回项目</button>
</div>
<!-- 调试信息面板 -->
<div class="debug-panel">
<div style="font-size: 12px; color: var(--vscode-input-foreground);">
<strong>调试信息:</strong>
<div id="debugInfo" class="debug-info">等待操作...</div>
</div>
</div>
<!-- URL 输入区域 -->
<div class="url-input-section">
<h3>🔗 添加 Git 仓库</h3>
<div style="display: flex; gap: 10px; margin-top: 10px;">
<input type="text" id="repoUrlInput"
placeholder="请输入 Git 仓库 URL例如: https://github.com/username/repo.git"
value="${repoUrl}"
style="flex: 1; padding: 8px; background: var(--vscode-input-background); color: var(--vscode-input-foreground); border: 1px solid var(--vscode-input-border); border-radius: 4px;">
<button class="btn-new" onclick="fetchBranches()">获取分支</button>
</div>
<div id="branchSelectionContainer">
${branchesHtml}
</div>
</div>
<div style="margin-bottom: 20px;">
${currentRepo ? `
<div class="current-repo">
<strong>当前仓库:</strong> ${currentRepo.name} (${currentRepo.url})
<button class="btn-sync" onclick="syncRepo('${currentRepo.id}')">同步</button>
</div>
` : ''}
</div>
<div class="git-container">
<div class="repo-list">
<table class="table">
<thead>
<tr>
<th width="60%">仓库</th>
<th width="20%">操作</th>
<th width="20%">管理</th>
</tr>
</thead>
<tbody>
${reposHtml}
</tbody>
</table>
</div>
<div class="file-tree">
<h3>📂 文件浏览器</h3>
${loading ? '<div class="loading">🔄 加载中...</div>' : fileTreeHtml}
</div>
</div>
<script>
let vscode;
let selectedBranches = new Set();
let currentRepoUrl = '';
try {
if (typeof window.vscodeInstance !== 'undefined') {
vscode = window.vscodeInstance;
} else if (typeof acquireVsCodeApi !== 'undefined') {
vscode = acquireVsCodeApi();
window.vscodeInstance = vscode;
}
} catch (error) {
console.error('获取 vscode API 失败:', error);
}
function updateDebugInfo(message) {
const debugElement = document.getElementById('debugInfo');
if (debugElement) {
debugElement.innerHTML = message;
console.log('🔍 调试信息:', message);
}
}
function fetchBranches() {
const urlInput = document.getElementById('repoUrlInput');
const repoUrl = urlInput.value.trim();
if (!repoUrl) {
alert('请输入 Git 仓库 URL');
return;
}
if (!repoUrl.startsWith('http')) {
alert('请输入有效的 Git 仓库 URL');
return;
}
currentRepoUrl = repoUrl;
console.log('🌿 获取分支列表:', repoUrl);
updateDebugInfo('🌿 正在获取分支列表...');
vscode.postMessage({
type: 'fetchBranches',
url: repoUrl
});
}
function toggleBranch(branchName) {
const checkbox = document.getElementById('branch-' + branchName.replace(/[^a-zA-Z0-9]/g, '-'));
if (checkbox.checked) {
selectedBranches.add(branchName);
} else {
selectedBranches.delete(branchName);
}
console.log('选中的分支:', Array.from(selectedBranches));
updateDebugInfo('选中的分支: ' + Array.from(selectedBranches).join(', '));
}
function cloneSelectedBranches() {
if (selectedBranches.size === 0) {
alert('请至少选择一个分支');
return;
}
console.log('🚀 开始克隆选中的分支:', Array.from(selectedBranches));
updateDebugInfo('🚀 开始克隆分支: ' + Array.from(selectedBranches).join(', '));
vscode.postMessage({
type: 'cloneBranches',
url: currentRepoUrl,
branches: Array.from(selectedBranches)
});
// 重置选择
selectedBranches.clear();
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => checkbox.checked = false);
// 隐藏分支选择区域
document.getElementById('branchSelectionContainer').innerHTML = '';
updateDebugInfo('✅ 分支克隆请求已发送');
}
function cancelBranchSelection() {
selectedBranches.clear();
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => checkbox.checked = false);
// 隐藏分支选择区域
document.getElementById('branchSelectionContainer').innerHTML = '';
updateDebugInfo('❌ 已取消分支选择');
vscode.postMessage({
type: 'cancelBranchSelection'
});
}
function loadRepo(repoId) {
console.log('📂 加载仓库:', repoId);
updateDebugInfo('📂 正在加载仓库...');
vscode.postMessage({
type: 'loadGitRepo',
repoId: repoId
});
}
function syncRepo(repoId) {
console.log('🔄 同步仓库:', repoId);
updateDebugInfo('🔄 正在同步仓库...');
vscode.postMessage({
type: 'syncGitRepo',
repoId: repoId
});
}
function deleteRepo(repoId) {
if (confirm('确定删除这个 Git 仓库吗?')) {
console.log('🗑️ 删除仓库:', repoId);
updateDebugInfo('🗑️ 正在删除仓库...');
vscode.postMessage({
type: 'deleteGitRepo',
repoId: repoId
});
}
}
function importFile(filePath) {
if (confirm('确定要将此文件导入到当前项目吗?')) {
console.log('📥 导入文件:', filePath);
updateDebugInfo('📥 正在导入文件...');
vscode.postMessage({
type: 'importGitFile',
filePath: filePath
});
}
}
function toggleFolder(folderPath) {
const folderElement = document.getElementById('folder-' + folderPath.replace(/[^a-zA-Z0-9]/g, '-'));
if (folderElement) {
folderElement.style.display = folderElement.style.display === 'none' ? 'block' : 'none';
}
}
function goBackToProjects() {
console.log('↩️ 返回项目页面');
updateDebugInfo('↩️ 正在返回项目页面...');
vscode.postMessage({
type: 'goBackToProjects'
});
}
// 动态渲染分支选择区域
function renderBranchSelection(branches, repoUrl) {
const container = document.getElementById('branchSelectionContainer');
if (branches.length === 0) {
container.innerHTML = '<div style="text-align: center; padding: 10px; color: var(--vscode-descriptionForeground);">未找到分支</div>';
return;
}
let branchesHtml = '<div class="branch-selection" style="margin: 15px 0; padding: 15px; background: var(--vscode-panel-background); border-radius: 4px;">';
branchesHtml += '<h4>🌿 选择要克隆的分支 (共 ' + branches.length + ' 个)</h4>';
branchesHtml += '<div style="max-height: 200px; overflow-y: auto; margin: 10px 0;">';
branches.forEach(branch => {
branchesHtml += '<div class="branch-item" style="padding: 8px; border-bottom: 1px solid var(--vscode-panel-border); display: flex; align-items: center;">';
branchesHtml += '<input type="checkbox" id="branch-' + branch.name.replace(/[^a-zA-Z0-9]/g, '-') + '" ';
branchesHtml += (branch.selected ? 'checked' : '') + ' onchange="toggleBranch(\\'' + branch.name + '\\')" style="margin-right: 10px;">';
branchesHtml += '<label for="branch-' + branch.name.replace(/[^a-zA-Z0-9]/g, '-') + '" style="flex: 1; cursor: pointer;">';
branchesHtml += (branch.isCurrent ? '⭐ ' : '') + branch.name;
branchesHtml += (branch.isRemote ? '(远程)' : '(本地)') + '</label></div>';
});
branchesHtml += '</div>';
branchesHtml += '<div style="margin-top: 15px;">';
branchesHtml += '<button class="btn-new" onclick="cloneSelectedBranches()" style="margin-right: 10px;">✅ 克隆选中分支</button>';
branchesHtml += '<button class="back-btn" onclick="cancelBranchSelection()">取消</button>';
branchesHtml += '</div></div>';
container.innerHTML = branchesHtml;
}
// 消息监听
window.addEventListener('message', event => {
const message = event.data;
console.log('📨 前端收到后端消息:', message);
updateDebugInfo('📨 收到后端消息: ' + message.type);
if (message.type === 'branchesFetched') {
console.log('🌿 收到分支数据:', message.branches);
updateDebugInfo('✅ 获取到 ' + message.branches.length + ' 个分支');
renderBranchSelection(message.branches, message.repoUrl);
}
if (message.type === 'gitRepoLoading') {
updateDebugInfo(message.loading ? '🔄 后端正在加载仓库文件树...' : '✅ 后端文件树加载完成');
}
if (message.type === 'testFromBackend') {
updateDebugInfo('✅ 前后端通信正常!消息: ' + message.message);
}
});
// 初始化
document.addEventListener('DOMContentLoaded', function() {
console.log('📄 GitView 页面加载完成');
updateDebugInfo('📄 页面加载完成 - 等待用户操作');
setTimeout(() => {
document.querySelectorAll('.tree-children').forEach(el => {
el.style.display = 'block';
});
}, 100);
});
</script>
</body>
</html>`;
}
generateBranchesHtml(branches) {
if (branches.length === 0)
return '';
let html = '<div class="branch-selection" style="margin: 15px 0; padding: 15px; background: var(--vscode-panel-background); border-radius: 4px;">';
html += '<h4>🌿 选择要克隆的分支 (共 ' + branches.length + ' 个)</h4>';
html += '<div style="max-height: 200px; overflow-y: auto; margin: 10px 0;">';
branches.forEach(branch => {
const branchId = 'branch-' + branch.name.replace(/[^a-zA-Z0-9]/g, '-');
html += '<div class="branch-item" style="padding: 8px; border-bottom: 1px solid var(--vscode-panel-border); display: flex; align-items: center;">';
html += '<input type="checkbox" id="' + branchId + '" ';
html += (branch.selected ? 'checked' : '') + ' onchange="toggleBranch(\'' + branch.name + '\')" style="margin-right: 10px;">';
html += '<label for="' + branchId + '" style="flex: 1; cursor: pointer;">';
html += (branch.isCurrent ? '⭐ ' : '') + branch.name;
html += (branch.isRemote ? '(远程)' : '(本地)') + '</label></div>';
});
html += '</div>';
html += '<div style="margin-top: 15px;">';
html += '<button class="btn-new" onclick="cloneSelectedBranches()" style="margin-right: 10px;">✅ 克隆选中分支</button>';
html += '<button class="back-btn" onclick="cancelBranchSelection()">取消</button>';
html += '</div></div>';
return html;
}
renderFileTree(nodes, level = 0) {
return nodes.map(node => {
const paddingLeft = level * 20;
if (node.type === 'folder') {
return `
<div class="tree-item" style="padding-left: ${paddingLeft}px;">
<span class="tree-folder" onclick="toggleFolder('${node.path}')">
📁 ${node.name}
</span>
<div id="folder-${node.path.replace(/[^a-zA-Z0-9]/g, '-')}" class="tree-children">
${this.renderFileTree(node.children || [], level + 1)}
</div>
</div>
`;
}
else {
return `
<div class="tree-item" style="padding-left: ${paddingLeft}px;">
<span class="tree-file clickable" onclick="importFile('${node.path}')">
📄 ${node.name}
</span>
</div>
`;
}
}).join('');
}
}
exports.GitView = GitView;
//# sourceMappingURL=GitView.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"GitView.js","sourceRoot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