0
0

添加了一个可视化仓库功能

This commit is contained in:
xubing
2025-12-02 12:52:41 +08:00
parent b94305476f
commit fb8e31babb
13 changed files with 740 additions and 396 deletions

View File

@@ -27,6 +27,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigPanel = void 0;
// src/panels/ConfigPanel.ts
const vscode = __importStar(require("vscode"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
@@ -71,6 +72,8 @@ class ConfigPanel {
this.moduleFolders = [];
this.currentModuleFolderFileTree = [];
this.projectPaths = new Map();
// 仓库配置
this.repoConfigs = [];
// 状态管理
this.isWebviewDisposed = false;
this.panel = panel;
@@ -81,6 +84,8 @@ class ConfigPanel {
this.aircraftView = new AircraftView_1.AircraftView(extensionUri);
this.containerView = new ContainerView_1.ContainerView(extensionUri);
this.configView = new ConfigView_1.ConfigView(extensionUri);
// 尝试加载仓库配置
void this.loadRepoConfigs();
this.updateWebview();
this.setupMessageListener();
this.panel.onDidDispose(() => {
@@ -108,6 +113,94 @@ class ConfigPanel {
return `${prefix}${idNumber}`;
}
// =============================================
// 仓库配置相关
// =============================================
getRepoConfigPath() {
// 按你的需求:配置文件保存在插件安装位置
return path.join(this.extensionUri.fsPath, 'dcsp-repos.json');
}
async loadRepoConfigs() {
try {
const configPath = this.getRepoConfigPath();
if (!fs.existsSync(configPath)) {
this.repoConfigs = [];
return;
}
const content = await fs.promises.readFile(configPath, 'utf8');
if (!content.trim()) {
this.repoConfigs = [];
return;
}
const parsed = JSON.parse(content);
if (Array.isArray(parsed)) {
// 兼容老格式:直接是数组
this.repoConfigs = parsed;
}
else if (parsed && Array.isArray(parsed.repos)) {
this.repoConfigs = parsed.repos;
}
else {
this.repoConfigs = [];
}
}
catch (error) {
console.error('加载仓库配置失败:', error);
vscode.window.showErrorMessage('读取仓库配置文件失败dcsp-repos.json请检查文件格式。');
this.repoConfigs = [];
}
}
async ensureRepoConfigFileExists() {
const configPath = this.getRepoConfigPath();
if (!fs.existsSync(configPath)) {
const defaultContent = JSON.stringify({
repos: [
{
name: 'example-repo',
url: 'https://github.com/username/repo.git',
username: '',
password: ''
}
]
}, null, 2);
await fs.promises.writeFile(configPath, defaultContent, 'utf8');
}
}
async openRepoConfig() {
try {
await this.ensureRepoConfigFileExists();
const configPath = this.getRepoConfigPath();
const doc = await vscode.workspace.openTextDocument(vscode.Uri.file(configPath));
await vscode.window.showTextDocument(doc);
await this.loadRepoConfigs();
}
catch (error) {
vscode.window.showErrorMessage(`打开仓库配置文件失败: ${error}`);
}
}
async openRepoSelect() {
await this.loadRepoConfigs();
if (!this.repoConfigs || this.repoConfigs.length === 0) {
vscode.window.showWarningMessage('尚未配置任何仓库,请先点击右上角 “仓库配置” 按钮编辑 dcsp-repos.json。');
}
if (this.isWebviewDisposed)
return;
// 仅传递仓库名给前端,用于下拉选择
this.panel.webview.postMessage({
type: 'showRepoSelect',
repos: this.repoConfigs.map(r => ({ name: r.name }))
});
}
async handleRepoSelectedForBranches(repoName) {
await this.loadRepoConfigs();
const repo = this.repoConfigs.find(r => r.name === repoName);
if (!repo) {
vscode.window.showErrorMessage(`在仓库配置中未找到名为 "${repoName}" 的仓库,请检查 dcsp-repos.json。`);
return;
}
this.currentRepoForBranches = repo;
await this.fetchBranchesForRepo(repo);
}
// =============================================
// Webview 消息处理
// =============================================
setupMessageListener() {
@@ -157,9 +250,13 @@ class ConfigPanel {
'deleteConfig': (data) => this.deleteConfig(data.configId),
'openConfigFileInVSCode': (data) => this.openConfigFileInVSCode(data.configId),
'mergeConfigs': (data) => this.mergeConfigs(data.configIds, data.displayName, data.folderName),
// Git 仓库管理
// Git 仓库管理(新:基于配置)
'openRepoConfig': () => this.openRepoConfig(),
'openRepoSelect': () => this.openRepoSelect(),
'repoSelectedForBranches': (data) => this.handleRepoSelectedForBranches(data.repoName),
// Git 仓库管理(老接口:为了兼容,仍然保留)
'fetchBranches': (data) => this.fetchBranches(data.url),
'cloneBranches': (data) => this.cloneBranches(data.url, data.branches),
'cloneBranches': (data) => this.cloneBranches(data.branches),
'cancelBranchSelection': () => this.handleCancelBranchSelection(),
// 模块文件夹管理
'loadModuleFolder': (data) => this.loadModuleFolder(data.folderId),
@@ -242,14 +339,12 @@ class ConfigPanel {
}
}
async createProject(name) {
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('p', this.projects);
const newProject = {
id: newId,
name: name
};
this.projects.push(newProject);
// 设置当前项目
this.currentProjectId = newId;
vscode.window.showInformationMessage(`新建项目: ${name}`);
this.updateWebview();
@@ -259,7 +354,6 @@ class ConfigPanel {
if (!project)
return;
this.projects = this.projects.filter(p => p.id !== projectId);
// 删除相关数据
const relatedAircrafts = this.aircrafts.filter(a => a.projectId === projectId);
const aircraftIds = relatedAircrafts.map(a => a.id);
this.aircrafts = this.aircrafts.filter(a => a.projectId !== projectId);
@@ -289,7 +383,6 @@ class ConfigPanel {
vscode.window.showErrorMessage('无法创建飞行器:未找到当前项目');
return;
}
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('a', this.aircrafts);
const newAircraft = {
id: newId,
@@ -332,7 +425,6 @@ class ConfigPanel {
vscode.window.showErrorMessage('无法创建容器:未找到当前飞行器');
return;
}
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('c', this.containers);
const newContainer = {
id: newId,
@@ -370,7 +462,6 @@ class ConfigPanel {
}
}
async createConfig(name) {
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('cfg', this.configs);
const newConfig = {
id: newId,
@@ -426,7 +517,6 @@ class ConfigPanel {
vscode.window.showErrorMessage('部分配置文件未找到');
return;
}
// 创建合并文件夹并复制文件
const mergeFolderPath = path.join(projectPath, aircraft.name, container.name, folderName);
await fs.promises.mkdir(mergeFolderPath, { recursive: true });
for (const config of selectedConfigs) {
@@ -439,9 +529,7 @@ class ConfigPanel {
await fs.promises.writeFile(targetPath, config.content || '');
}
}
// 创建合并文件夹记录
const relativePath = `/${aircraft.projectId}/${aircraft.name}/${container.name}/${folderName}`;
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('local-', this.moduleFolders);
const newFolder = {
id: newId,
@@ -451,7 +539,6 @@ class ConfigPanel {
containerId: this.currentContainerId
};
this.moduleFolders.push(newFolder);
// 删除原始配置文件
for (const configId of configIds) {
await this.deleteConfigInternal(configId);
}
@@ -467,7 +554,10 @@ class ConfigPanel {
// =============================================
// Git 分支管理方法
// =============================================
async fetchBranches(url) {
async fetchBranchesForRepo(repo) {
await this.fetchBranches(repo.url, repo);
}
async fetchBranches(url, repo) {
try {
console.log('🌿 开始获取分支列表:', url);
await vscode.window.withProgress({
@@ -478,15 +568,20 @@ class ConfigPanel {
progress.report({ increment: 0, message: '连接远程仓库...' });
try {
progress.report({ increment: 30, message: '获取远程引用...' });
const refs = await isomorphic_git_1.default.listServerRefs({
const options = {
http: node_1.default,
url: url
});
};
if (repo && (repo.username || repo.password)) {
options.onAuth = () => ({
username: repo.username || '',
password: repo.password || ''
});
}
const refs = await isomorphic_git_1.default.listServerRefs(options);
console.log('📋 获取到的引用:', refs);
// 过滤出分支引用
const branchRefs = refs.filter(ref => ref.ref.startsWith('refs/heads/') || ref.ref.startsWith('refs/remotes/origin/'));
// 构建分支数据
const branches = branchRefs.map(ref => {
const branchRefs = refs.filter((ref) => ref.ref.startsWith('refs/heads/') || ref.ref.startsWith('refs/remotes/origin/'));
const branches = branchRefs.map((ref) => {
let branchName;
if (ref.ref.startsWith('refs/remotes/')) {
branchName = ref.ref.replace('refs/remotes/origin/', '');
@@ -504,15 +599,14 @@ class ConfigPanel {
throw new Error('未找到任何分支');
}
progress.report({ increment: 80, message: '处理分支数据...' });
// 构建分支树状结构
const branchTree = this.buildBranchTree(branches);
// 发送分支数据到前端
if (!this.isWebviewDisposed) {
this.panel.webview.postMessage({
type: 'branchesFetched',
branches: branches,
branchTree: branchTree,
repoUrl: url
repoUrl: url,
repoName: repo?.name
});
}
progress.report({ increment: 100, message: '完成' });
@@ -528,7 +622,13 @@ class ConfigPanel {
vscode.window.showErrorMessage(`获取分支失败: ${error}`);
}
}
async cloneBranches(url, branches) {
async cloneBranches(branches) {
if (!this.currentRepoForBranches) {
vscode.window.showErrorMessage('请先通过“获取仓库”选择一个仓库');
return;
}
const url = this.currentRepoForBranches.url;
const repoDisplayName = this.currentRepoForBranches.name;
try {
console.log('🚀 开始克隆分支:', { url, branches });
let successCount = 0;
@@ -548,7 +648,7 @@ class ConfigPanel {
console.log(`📥 开始克隆分支: ${branch}`);
try {
const folderNames = this.generateModuleFolderName(url, branch);
await this.addGitModuleFolder(url, folderNames.displayName, folderNames.folderName, branch);
await this.addGitModuleFolder(url, repoDisplayName, folderNames.folderName, branch);
successCount++;
console.log(`✅ 分支克隆成功: ${branch}`);
}
@@ -558,7 +658,6 @@ class ConfigPanel {
}
}
});
// 显示最终结果
if (failCount === 0) {
vscode.window.showInformationMessage(`成功克隆 ${successCount} 个分支`);
}
@@ -591,12 +690,10 @@ class ConfigPanel {
vscode.window.showErrorMessage('未找到相关项目数据');
return;
}
// 使用新的 ID 生成方法
const folderId = this.generateUniqueId('git-', this.moduleFolders);
const relativePath = `/${aircraft.projectId}/${aircraft.name}/${container.name}/${folderName}`;
const localPath = path.join(projectPath, aircraft.name, container.name, folderName);
console.log(`📁 准备克隆仓库: ${displayName}, 分支: ${branch}, 路径: ${localPath}`);
// 检查是否已存在相同路径的模块文件夹
const existingFolder = this.moduleFolders.find(folder => folder.localPath === relativePath && folder.containerId === this.currentContainerId);
if (existingFolder) {
vscode.window.showWarningMessage(`该路径的模块文件夹已存在: ${folderName}`);
@@ -616,10 +713,8 @@ class ConfigPanel {
}, async (progress) => {
progress.report({ increment: 0 });
try {
// 确保父目录存在
const parentDir = path.dirname(localPath);
await fs.promises.mkdir(parentDir, { recursive: true });
// 检查目标目录是否已存在
let dirExists = false;
try {
await fs.promises.access(localPath);
@@ -636,7 +731,6 @@ class ConfigPanel {
vscode.window.showInformationMessage('克隆操作已取消');
return;
}
// 清空目录(除了 .git 文件夹)
for (const item of dirContents) {
const itemPath = path.join(localPath, item);
if (item !== '.git') {
@@ -646,7 +740,6 @@ class ConfigPanel {
}
}
console.log(`🚀 开始克隆: ${url} -> ${localPath}, 分支: ${branch}`);
// 克隆仓库
await isomorphic_git_1.default.clone({
fs: fs,
http: node_1.default,
@@ -670,18 +763,15 @@ class ConfigPanel {
}
});
console.log('✅ Git克隆成功完成');
// 验证克隆是否真的成功
const clonedContents = await fs.promises.readdir(localPath);
console.log(`📁 克隆后的目录内容:`, clonedContents);
if (clonedContents.length === 0) {
throw new Error('克隆后目录为空,可能克隆失败');
}
// 只有在克隆成功后才添加到列表
this.moduleFolders.push(newFolder);
await this.saveCurrentProjectData();
console.log('✅ Git模块文件夹数据已保存到项目文件');
vscode.window.showInformationMessage(`Git 仓库克隆成功: ${displayName}`);
// 自动加载文件树
if (!this.isWebviewDisposed) {
console.log('🌳 开始加载模块文件夹文件树...');
this.currentModuleFolderId = folderId;
@@ -691,7 +781,6 @@ class ConfigPanel {
}
catch (error) {
console.error('❌ 在克隆过程中捕获错误:', error);
// 清理:如果克隆失败,删除可能创建的不完整目录
try {
if (fs.existsSync(localPath)) {
await fs.promises.rm(localPath, { recursive: true, force: true });
@@ -802,7 +891,6 @@ class ConfigPanel {
const fileFullPath = path.join(fullPath, filePath);
const content = await fs.promises.readFile(fileFullPath, 'utf8');
const fileName = path.basename(filePath);
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('cfg', this.configs);
const newConfig = {
id: newId,
@@ -850,7 +938,7 @@ class ConfigPanel {
}
catch (error) {
console.error('❌ Git 上传失败:', error);
vscode.window.showErrorMessage(`推送失败: ${error.message}`);
vscode.window.showErrorMessage(`推送失败: ${error.message || error}`);
}
});
}
@@ -892,8 +980,7 @@ class ConfigPanel {
}
catch (error) {
console.error('❌ 本地文件夹上传失败:', error);
vscode.window.showErrorMessage(`推送失败: ${error.message}`);
// 清理:删除可能创建的 .git 文件夹
vscode.window.showErrorMessage(`推送失败: ${error.message || error}`);
try {
const gitDir = path.join(fullPath, '.git');
if (fs.existsSync(gitDir)) {
@@ -914,7 +1001,6 @@ class ConfigPanel {
const { exec } = require('child_process');
console.log('🚀 使用命令行 Git 提交并推送...');
console.log(`📁 工作目录: ${fullPath}`);
// 先检查是否有更改
exec('git status --porcelain', {
cwd: fullPath,
encoding: 'utf8'
@@ -924,14 +1010,12 @@ class ConfigPanel {
reject(new Error(`检查 Git 状态失败: ${statusStderr || statusError.message}`));
return;
}
// 如果没有更改
if (!statusStdout.trim()) {
console.log(' 没有需要提交的更改');
reject(new Error('没有需要提交的更改'));
return;
}
console.log('📋 检测到更改:', statusStdout);
// 有更改时才提交并推送
const commands = [
'git add .',
`git commit -m "Auto commit from DCSP - ${new Date().toLocaleString()}"`,
@@ -996,14 +1080,13 @@ class ConfigPanel {
console.log('💾 提交初始文件...');
const commands = [
'git add .',
`git commit -m "Initial commit from DCSP - ${new Date().toLocaleString()}"`
`git commit -m "Initial commit from DCSP - ${new Date().toLocaleString()}"`,
];
exec(commands.join(' && '), {
cwd: fullPath,
encoding: 'utf8'
}, (error, stdout, stderr) => {
if (error) {
// 检查是否是"没有更改可提交"的错误
if (stderr.includes('nothing to commit') || stdout.includes('nothing to commit')) {
console.log(' 没有需要提交的更改');
resolve();
@@ -1099,8 +1182,6 @@ class ConfigPanel {
}
}
async createDefaultConfigs(container) {
const configCount = this.configs.length;
// 第一个配置文件
this.configs.push({
id: this.generateUniqueId('cfg', this.configs),
name: '配置1',
@@ -1108,12 +1189,11 @@ class ConfigPanel {
content: `# ${container.name} 的 Dockerfile\nFROM ubuntu:20.04\n\n# 设置工作目录\nWORKDIR /app\n\n# 复制文件\nCOPY . .\n\n# 安装依赖\nRUN apt-get update && apt-get install -y \\\n python3 \\\n python3-pip\n\n# 暴露端口\nEXPOSE 8080\n\n# 启动命令\nCMD ["python3", "app.py"]`,
containerId: container.id
});
// 第二个配置文件
this.configs.push({
id: this.generateUniqueId('cfg', this.configs),
name: '配置2',
fileName: 'docker-compose.yml',
content: `# ${container.name} 的 Docker Compose 配置\nversion: '3.8'\n\nservices:\n ${container.name.toLowerCase().replace(/\\s+/g, '-')}:\n build: .\n container_name: ${container.name}\n ports:\n - "8080:8080"\n environment:\n - NODE_ENV=production\n volumes:\n - ./data:/app/data\n restart: unless-stopped`,
content: `# ${container.name} 的 Docker Compose 配置\nversion: '3.8'\n\nservices:\n ${container.name.toLowerCase().replace(/\s+/g, '-')}:\n build: .\n container_name: ${container.name}\n ports:\n - "8080:8080"\n environment:\n - NODE_ENV=production\n volumes:\n - ./data:/app/data\n restart: unless-stopped`,
containerId: container.id
});
}
@@ -1161,7 +1241,6 @@ class ConfigPanel {
return;
}
const dataUri = vscode.Uri.joinPath(vscode.Uri.file(projectPath), '.dcsp-data.json');
// 构建当前项目的完整数据
const data = {
projects: [this.projects.find(p => p.id === this.currentProjectId)],
aircrafts: this.aircrafts.filter(a => a.projectId === this.currentProjectId),
@@ -1195,7 +1274,6 @@ class ConfigPanel {
async loadProjectData(projectPath) {
try {
const dataUri = vscode.Uri.joinPath(vscode.Uri.file(projectPath), '.dcsp-data.json');
// 检查数据文件是否存在
try {
await vscode.workspace.fs.stat(dataUri);
}
@@ -1203,14 +1281,11 @@ class ConfigPanel {
vscode.window.showErrorMessage('选择的文件夹中没有找到项目数据文件 (.dcsp-data.json)');
return false;
}
// 读取数据文件
const fileData = await vscode.workspace.fs.readFile(dataUri);
const dataStr = new TextDecoder().decode(fileData);
const data = JSON.parse(dataStr);
// 只清空当前项目相关的数据,保留其他项目数据
const projectId = data.projects[0]?.id;
if (projectId) {
// 移除当前项目的旧数据
this.projects = this.projects.filter(p => p.id !== projectId);
this.aircrafts = this.aircrafts.filter(a => a.projectId !== projectId);
const aircraftIds = this.aircrafts.filter(a => a.projectId === projectId).map(a => a.id);
@@ -1218,13 +1293,11 @@ class ConfigPanel {
const containerIds = this.containers.filter(c => aircraftIds.includes(c.aircraftId)).map(c => c.id);
this.configs = this.configs.filter(cfg => !containerIds.includes(cfg.containerId));
this.moduleFolders = this.moduleFolders.filter(folder => !containerIds.includes(folder.containerId));
// 添加新数据
this.projects.push(...data.projects);
this.aircrafts.push(...data.aircrafts);
this.containers.push(...data.containers);
this.configs.push(...data.configs);
this.moduleFolders.push(...data.moduleFolders);
// 设置当前项目
this.currentProjectId = projectId;
this.projectPaths.set(projectId, projectPath);
this.currentView = 'aircrafts';
@@ -1370,7 +1443,6 @@ class ConfigPanel {
const folder = this.moduleFolders.find(f => f.id === folderId);
if (!folder)
return;
// 通知前端开始加载
try {
this.panel.webview.postMessage({
type: 'moduleFolderLoading',
@@ -1392,12 +1464,10 @@ class ConfigPanel {
console.error('加载模块文件夹文件树失败:', error);
this.currentModuleFolderFileTree = [];
}
// 再次检查 Webview 状态
if (this.isWebviewDisposed) {
console.log('⚠️ Webview 已被销毁,跳过完成通知');
return;
}
// 通知前端加载完成
try {
this.panel.webview.postMessage({
type: 'moduleFolderLoading',
@@ -1414,7 +1484,6 @@ class ConfigPanel {
const files = await fs.promises.readdir(dir);
const tree = [];
for (const file of files) {
// 忽略 .git 文件夹和 .dcsp-data.json
if (file.startsWith('.') && file !== '.git')
continue;
if (file === '.dcsp-data.json')
@@ -1583,7 +1652,6 @@ class ConfigPanel {
projectPaths: this.projectPaths
});
case 'aircrafts':
// 只显示当前项目的飞行器
const projectAircrafts = this.aircrafts.filter(a => a.projectId === this.currentProjectId);
return this.aircraftView.render({
aircrafts: projectAircrafts
@@ -1591,7 +1659,6 @@ class ConfigPanel {
case 'containers':
const currentProject = this.projects.find(p => p.id === this.currentProjectId);
const currentAircraft = this.aircrafts.find(a => a.id === this.currentAircraftId);
// 只显示当前飞行器的容器
const projectContainers = this.containers.filter(c => c.aircraftId === this.currentAircraftId);
return this.containerView.render({
project: currentProject,
@@ -1600,9 +1667,8 @@ 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 currentModuleFolder = this.moduleFolders.find(f => f.id === this.currentModuleFolderId);
const containerConfigs = this.configs.filter(cfg => cfg.containerId === this.currentContainerId);
const containerModuleFolders = this.moduleFolders.filter(folder => folder.containerId === this.currentContainerId);
return this.configView.render({
container: currentContainer,