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

@@ -1,3 +1,4 @@
// src/panels/ConfigPanel.ts
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
@@ -59,6 +60,14 @@ interface ProjectData {
moduleFolders: ModuleFolder[];
}
// 仓库配置项
interface RepoConfigItem {
name: string;
url: string;
username?: string;
password?: string;
}
// =============================================
// 主面板类
// =============================================
@@ -84,6 +93,10 @@ export class ConfigPanel {
private currentModuleFolderFileTree: GitFileTree[] = [];
private projectPaths: Map<string, string> = new Map();
// 仓库配置
private repoConfigs: RepoConfigItem[] = [];
private currentRepoForBranches: RepoConfigItem | undefined;
// 状态管理
private isWebviewDisposed: boolean = false;
@@ -130,6 +143,9 @@ export class ConfigPanel {
this.containerView = new ContainerView(extensionUri);
this.configView = new ConfigView(extensionUri);
// 尝试加载仓库配置
void this.loadRepoConfigs();
this.updateWebview();
this.setupMessageListener();
@@ -163,6 +179,106 @@ export class ConfigPanel {
return `${prefix}${idNumber}`;
}
// =============================================
// 仓库配置相关
// =============================================
private getRepoConfigPath(): string {
// 按你的需求:配置文件保存在插件安装位置
return path.join(this.extensionUri.fsPath, 'dcsp-repos.json');
}
private async loadRepoConfigs(): Promise<void> {
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 = [];
}
}
private async ensureRepoConfigFileExists(): Promise<void> {
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');
}
}
private async openRepoConfig(): Promise<void> {
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}`);
}
}
private async openRepoSelect(): Promise<void> {
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 }))
});
}
private async handleRepoSelectedForBranches(repoName: string): Promise<void> {
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 消息处理
// =============================================
@@ -221,9 +337,14 @@ export class ConfigPanel {
'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(),
// 模块文件夹管理
@@ -320,7 +441,6 @@ export class ConfigPanel {
}
private async createProject(name: string): Promise<void> {
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('p', this.projects);
const newProject: Project = {
id: newId,
@@ -328,7 +448,6 @@ export class ConfigPanel {
};
this.projects.push(newProject);
// 设置当前项目
this.currentProjectId = newId;
vscode.window.showInformationMessage(`新建项目: ${name}`);
@@ -341,7 +460,6 @@ export class ConfigPanel {
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);
@@ -379,7 +497,6 @@ export class ConfigPanel {
return;
}
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('a', this.aircrafts);
const newAircraft: Aircraft = {
id: newId,
@@ -430,7 +547,6 @@ export class ConfigPanel {
return;
}
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('c', this.containers);
const newContainer: Container = {
id: newId,
@@ -475,7 +591,6 @@ export class ConfigPanel {
}
private async createConfig(name: string): Promise<void> {
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('cfg', this.configs);
const newConfig: Config = {
id: newId,
@@ -547,7 +662,6 @@ export class ConfigPanel {
return;
}
// 创建合并文件夹并复制文件
const mergeFolderPath = path.join(projectPath, aircraft.name, container.name, folderName);
await fs.promises.mkdir(mergeFolderPath, { recursive: true });
@@ -562,9 +676,7 @@ export class ConfigPanel {
}
}
// 创建合并文件夹记录
const relativePath = `/${aircraft.projectId}/${aircraft.name}/${container.name}/${folderName}`;
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('local-', this.moduleFolders);
const newFolder: ModuleFolder = {
id: newId,
@@ -576,7 +688,6 @@ export class ConfigPanel {
this.moduleFolders.push(newFolder);
// 删除原始配置文件
for (const configId of configIds) {
await this.deleteConfigInternal(configId);
}
@@ -595,7 +706,11 @@ export class ConfigPanel {
// Git 分支管理方法
// =============================================
private async fetchBranches(url: string): Promise<void> {
private async fetchBranchesForRepo(repo: RepoConfigItem): Promise<void> {
await this.fetchBranches(repo.url, repo);
}
private async fetchBranches(url: string, repo?: RepoConfigItem): Promise<void> {
try {
console.log('🌿 开始获取分支列表:', url);
@@ -608,21 +723,28 @@ export class ConfigPanel {
try {
progress.report({ increment: 30, message: '获取远程引用...' });
const refs = await git.listServerRefs({
const options: any = {
http: http,
url: url
});
};
if (repo && (repo.username || repo.password)) {
options.onAuth = () => ({
username: repo.username || '',
password: repo.password || ''
});
}
const refs = await git.listServerRefs(options);
console.log('📋 获取到的引用:', refs);
// 过滤出分支引用
const branchRefs = refs.filter(ref =>
const branchRefs = refs.filter((ref: any) =>
ref.ref.startsWith('refs/heads/') || ref.ref.startsWith('refs/remotes/origin/')
);
// 构建分支数据
const branches: GitBranch[] = branchRefs.map(ref => {
const branches: GitBranch[] = branchRefs.map((ref: any) => {
let branchName: string;
if (ref.ref.startsWith('refs/remotes/')) {
@@ -644,16 +766,15 @@ export class ConfigPanel {
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
});
}
@@ -671,7 +792,15 @@ export class ConfigPanel {
}
}
private async cloneBranches(url: string, branches: string[]): Promise<void> {
private async cloneBranches(branches: string[]): Promise<void> {
if (!this.currentRepoForBranches) {
vscode.window.showErrorMessage('请先通过“获取仓库”选择一个仓库');
return;
}
const url = this.currentRepoForBranches.url;
const repoDisplayName = this.currentRepoForBranches.name;
try {
console.log('🚀 开始克隆分支:', { url, branches });
@@ -694,7 +823,7 @@ export 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}`);
} catch (error) {
@@ -704,7 +833,6 @@ export class ConfigPanel {
}
});
// 显示最终结果
if (failCount === 0) {
vscode.window.showInformationMessage(`成功克隆 ${successCount} 个分支`);
} else {
@@ -742,14 +870,12 @@ export class ConfigPanel {
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
);
@@ -774,11 +900,9 @@ export class ConfigPanel {
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);
@@ -802,7 +926,6 @@ export class ConfigPanel {
return;
}
// 清空目录(除了 .git 文件夹)
for (const item of dirContents) {
const itemPath = path.join(localPath, item);
if (item !== '.git') {
@@ -814,7 +937,6 @@ export class ConfigPanel {
console.log(`🚀 开始克隆: ${url} -> ${localPath}, 分支: ${branch}`);
// 克隆仓库
await git.clone({
fs: fs,
http: http,
@@ -839,7 +961,6 @@ export class ConfigPanel {
console.log('✅ Git克隆成功完成');
// 验证克隆是否真的成功
const clonedContents = await fs.promises.readdir(localPath);
console.log(`📁 克隆后的目录内容:`, clonedContents);
@@ -847,14 +968,12 @@ export class ConfigPanel {
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;
@@ -865,7 +984,6 @@ export class ConfigPanel {
} catch (error) {
console.error('❌ 在克隆过程中捕获错误:', error);
// 清理:如果克隆失败,删除可能创建的不完整目录
try {
if (fs.existsSync(localPath)) {
await fs.promises.rm(localPath, { recursive: true, force: true });
@@ -998,7 +1116,6 @@ export class ConfigPanel {
const content = await fs.promises.readFile(fileFullPath, 'utf8');
const fileName = path.basename(filePath);
// 使用新的 ID 生成方法
const newId = this.generateUniqueId('cfg', this.configs);
const newConfig: Config = {
id: newId,
@@ -1023,7 +1140,7 @@ export class ConfigPanel {
// 上传功能方法
// =============================================
private async uploadGitModuleFolder(folderId: string, username: string, password: string): Promise<void> {
private async uploadGitModuleFolder(folderId: string, username?: string, password?: string): Promise<void> {
const folder = this.moduleFolders.find(f => f.id === folderId);
if (!folder || folder.type !== 'git') {
vscode.window.showErrorMessage('未找到指定的 Git 模块文件夹');
@@ -1054,9 +1171,9 @@ export class ConfigPanel {
vscode.window.showInformationMessage(`✅ Git 仓库上传成功: ${folder.name}`);
this.updateWebview();
} catch (error) {
} catch (error: any) {
console.error('❌ Git 上传失败:', error);
vscode.window.showErrorMessage(`推送失败: ${error.message}`);
vscode.window.showErrorMessage(`推送失败: ${error.message || error}`);
}
});
}
@@ -1107,11 +1224,10 @@ export class ConfigPanel {
vscode.window.showInformationMessage(`本地文件夹成功上传到 Git 仓库: ${folder.name} -> ${branchName}`);
this.updateWebview();
} catch (error) {
} catch (error: any) {
console.error('❌ 本地文件夹上传失败:', error);
vscode.window.showErrorMessage(`推送失败: ${error.message}`);
vscode.window.showErrorMessage(`推送失败: ${error.message || error}`);
// 清理:删除可能创建的 .git 文件夹
try {
const gitDir = path.join(fullPath, '.git');
if (fs.existsSync(gitDir)) {
@@ -1135,18 +1251,16 @@ export class ConfigPanel {
console.log('🚀 使用命令行 Git 提交并推送...');
console.log(`📁 工作目录: ${fullPath}`);
// 先检查是否有更改
exec('git status --porcelain', {
cwd: fullPath,
encoding: 'utf8'
}, (statusError, statusStdout, statusStderr) => {
}, (statusError: any, statusStdout: string, statusStderr: string) => {
if (statusError) {
console.error('❌ 检查 Git 状态失败:', statusError);
reject(new Error(`检查 Git 状态失败: ${statusStderr || statusError.message}`));
return;
}
// 如果没有更改
if (!statusStdout.trim()) {
console.log(' 没有需要提交的更改');
reject(new Error('没有需要提交的更改'));
@@ -1155,7 +1269,6 @@ export class ConfigPanel {
console.log('📋 检测到更改:', statusStdout);
// 有更改时才提交并推送
const commands = [
'git add .',
`git commit -m "Auto commit from DCSP - ${new Date().toLocaleString()}"`,
@@ -1165,7 +1278,7 @@ export class ConfigPanel {
exec(commands.join(' && '), {
cwd: fullPath,
encoding: 'utf8'
}, (error, stdout, stderr) => {
}, (error: any, stdout: string, stderr: string) => {
console.log('📋 Git 命令输出:', stdout);
console.log('📋 Git 命令错误:', stderr);
@@ -1191,7 +1304,7 @@ export class ConfigPanel {
exec(`git init && git checkout -b ${branchName}`, {
cwd: fullPath,
encoding: 'utf8'
}, (error, stdout, stderr) => {
}, (error: any, stdout: string, stderr: string) => {
if (error) {
console.error('❌ Git 初始化失败:', error);
reject(new Error(stderr || error.message));
@@ -1213,7 +1326,7 @@ export class ConfigPanel {
exec(`git remote add origin ${repoUrl}`, {
cwd: fullPath,
encoding: 'utf8'
}, (error, stdout, stderr) => {
}, (error: any, stdout: string, stderr: string) => {
if (error) {
console.error('❌ 添加远程仓库失败:', error);
reject(new Error(stderr || error.message));
@@ -1234,15 +1347,14 @@ export class ConfigPanel {
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) => {
}, (error: any, stdout: string, stderr: string) => {
if (error) {
// 检查是否是"没有更改可提交"的错误
if (stderr.includes('nothing to commit') || stdout.includes('nothing to commit')) {
console.log(' 没有需要提交的更改');
resolve();
@@ -1269,7 +1381,7 @@ export class ConfigPanel {
exec(`git push -u origin ${branchName} --force`, {
cwd: fullPath,
encoding: 'utf8'
}, (error, stdout, stderr) => {
}, (error: any, stdout: string, stderr: string) => {
console.log('📋 Git push stdout:', stdout);
console.log('📋 Git push stderr:', stderr);
@@ -1355,9 +1467,6 @@ export class ConfigPanel {
}
private async createDefaultConfigs(container: Container): Promise<void> {
const configCount = this.configs.length;
// 第一个配置文件
this.configs.push({
id: this.generateUniqueId('cfg', this.configs),
name: '配置1',
@@ -1366,12 +1475,11 @@ export class ConfigPanel {
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
});
}
@@ -1427,9 +1535,8 @@ export class ConfigPanel {
const dataUri = vscode.Uri.joinPath(vscode.Uri.file(projectPath), '.dcsp-data.json');
// 构建当前项目的完整数据
const data: ProjectData = {
projects: [this.projects.find(p => p.id === this.currentProjectId)!], // 只保存当前项目
projects: [this.projects.find(p => p.id === this.currentProjectId)!],
aircrafts: this.aircrafts.filter(a => a.projectId === this.currentProjectId),
containers: this.containers.filter(c => {
const aircraft = this.aircrafts.find(a => a.id === c.aircraftId);
@@ -1462,7 +1569,6 @@ export class ConfigPanel {
try {
const dataUri = vscode.Uri.joinPath(vscode.Uri.file(projectPath), '.dcsp-data.json');
// 检查数据文件是否存在
try {
await vscode.workspace.fs.stat(dataUri);
} catch {
@@ -1470,15 +1576,12 @@ export class ConfigPanel {
return false;
}
// 读取数据文件
const fileData = await vscode.workspace.fs.readFile(dataUri);
const dataStr = new TextDecoder().decode(fileData);
const data: ProjectData = 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);
@@ -1489,14 +1592,12 @@ export class ConfigPanel {
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';
@@ -1666,7 +1767,6 @@ export class ConfigPanel {
const folder = this.moduleFolders.find(f => f.id === folderId);
if (!folder) return;
// 通知前端开始加载
try {
this.panel.webview.postMessage({
type: 'moduleFolderLoading',
@@ -1689,13 +1789,11 @@ export class ConfigPanel {
this.currentModuleFolderFileTree = [];
}
// 再次检查 Webview 状态
if (this.isWebviewDisposed) {
console.log('⚠️ Webview 已被销毁,跳过完成通知');
return;
}
// 通知前端加载完成
try {
this.panel.webview.postMessage({
type: 'moduleFolderLoading',
@@ -1714,7 +1812,6 @@ export class ConfigPanel {
const tree: GitFileTree[] = [];
for (const file of files) {
// 忽略 .git 文件夹和 .dcsp-data.json
if (file.startsWith('.') && file !== '.git') continue;
if (file === '.dcsp-data.json') continue;
@@ -1907,7 +2004,6 @@ export class ConfigPanel {
projectPaths: this.projectPaths
});
case 'aircrafts':
// 只显示当前项目的飞行器
const projectAircrafts = this.aircrafts.filter(a => a.projectId === this.currentProjectId);
return this.aircraftView.render({
aircrafts: projectAircrafts
@@ -1915,7 +2011,6 @@ export 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({
@@ -1925,9 +2020,8 @@ export 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({
@@ -1945,4 +2039,4 @@ export class ConfigPanel {
});
}
}
}
}