0
0
Files
dscp/src/panels/ConfigPanel.ts

1552 lines
60 KiB
TypeScript
Raw Normal View History

2025-12-04 10:16:57 +08:00
// src/panels/ConfigPanel.ts
2025-11-18 09:10:47 +08:00
import * as vscode from 'vscode';
import * as path from 'path';
2025-11-18 18:45:30 +08:00
import { ProjectView } from './views/ProjectView';
import { AircraftView } from './views/AircraftView';
import { ContainerView } from './views/ContainerView';
import { ConfigView } from './views/ConfigView';
2025-12-03 16:08:14 +08:00
import { ProjectService } from './services/ProjectService';
import { GitService } from './services/GitService';
import { StorageService } from './services/StorageService';
2025-11-28 14:58:18 +08:00
import { ModuleFolder } from './types/CommonTypes';
2025-11-18 09:10:47 +08:00
2025-12-03 16:08:14 +08:00
// 仓库配置项接口
interface RepoConfigItem {
2025-11-18 09:10:47 +08:00
name: string;
2025-12-03 16:08:14 +08:00
url: string;
username?: string;
token?: string;
2025-11-18 09:10:47 +08:00
}
2025-12-03 16:08:14 +08:00
// Git文件树接口
interface GitFileTree {
name: string;
type: 'file' | 'folder';
path: string;
children?: GitFileTree[];
}
2025-11-18 09:10:47 +08:00
export class ConfigPanel {
public static currentPanel: ConfigPanel | undefined;
public readonly panel: vscode.WebviewPanel;
2025-11-18 09:10:47 +08:00
private readonly extensionUri: vscode.Uri;
2025-12-03 16:08:14 +08:00
// 服务实例
private projectService: ProjectService;
// 视图状态管理
2025-11-18 18:45:30 +08:00
private currentView: 'projects' | 'aircrafts' | 'containers' | 'configs' = 'projects';
2025-11-18 09:10:47 +08:00
private currentProjectId: string = '';
private currentAircraftId: string = '';
private currentContainerId: string = '';
2025-11-27 22:04:32 +08:00
private currentModuleFolderId: string = '';
2025-11-18 09:10:47 +08:00
2025-12-02 12:52:41 +08:00
// 仓库配置
private repoConfigs: RepoConfigItem[] = [];
private currentRepoForBranches: RepoConfigItem | undefined;
// 状态管理
private isWebviewDisposed: boolean = false;
2025-12-03 16:08:14 +08:00
private currentModuleFolderFileTree: GitFileTree[] = [];
2025-11-18 09:10:47 +08:00
// 视图实例
2025-11-18 18:45:30 +08:00
private readonly projectView: ProjectView;
private readonly aircraftView: AircraftView;
private readonly containerView: ContainerView;
private readonly configView: ConfigView;
2025-11-18 09:10:47 +08:00
// =============================================
// 公共方法
// =============================================
2025-11-18 09:10:47 +08:00
public static createOrShow(extensionUri: vscode.Uri) {
const column = vscode.window.activeTextEditor?.viewColumn || vscode.ViewColumn.One;
if (ConfigPanel.currentPanel) {
ConfigPanel.currentPanel.panel.reveal(column);
return;
}
const panel = vscode.window.createWebviewPanel(
2025-11-18 18:45:30 +08:00
'DCSP',
'数字卫星构建平台',
2025-11-18 09:10:47 +08:00
column,
{
enableScripts: true,
localResourceRoots: [extensionUri],
retainContextWhenHidden: true
}
);
ConfigPanel.currentPanel = new ConfigPanel(panel, extensionUri);
}
public constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
2025-11-18 09:10:47 +08:00
this.panel = panel;
this.extensionUri = extensionUri;
this.isWebviewDisposed = false;
2025-11-18 09:10:47 +08:00
2025-12-03 16:08:14 +08:00
// 初始化服务
this.projectService = new ProjectService();
// 初始化视图
2025-11-18 18:45:30 +08:00
this.projectView = new ProjectView(extensionUri);
this.aircraftView = new AircraftView(extensionUri);
this.containerView = new ContainerView(extensionUri);
this.configView = new ConfigView(extensionUri);
2025-11-18 09:10:47 +08:00
2025-12-03 16:08:14 +08:00
// 加载仓库配置
2025-12-02 12:52:41 +08:00
void this.loadRepoConfigs();
2025-11-18 09:10:47 +08:00
this.updateWebview();
this.setupMessageListener();
this.panel.onDidDispose(() => {
this.isWebviewDisposed = true;
2025-11-18 09:10:47 +08:00
ConfigPanel.currentPanel = undefined;
});
}
2025-12-02 12:52:41 +08:00
// =============================================
// 仓库配置相关
// =============================================
private async loadRepoConfigs(): Promise<void> {
2025-12-03 16:08:14 +08:00
this.repoConfigs = await StorageService.loadRepoConfigs(this.extensionUri);
2025-12-02 12:52:41 +08:00
}
private async openRepoConfig(): Promise<void> {
2025-12-03 16:08:14 +08:00
await StorageService.openRepoConfig(this.extensionUri);
await this.loadRepoConfigs();
2025-12-02 12:52:41 +08:00
}
/**
* ->
*/
2025-12-02 12:52:41 +08:00
private async openRepoSelect(): Promise<void> {
await this.loadRepoConfigs();
2025-12-03 16:08:14 +08:00
if (this.repoConfigs.length === 0) {
vscode.window.showWarningMessage('尚未配置任何仓库,请先点击右上角 "仓库配置" 按钮编辑 dcsp-repos.json。');
return;
2025-12-02 12:52:41 +08:00
}
if (this.isWebviewDisposed) return;
this.panel.webview.postMessage({
type: 'showRepoSelect',
repos: this.repoConfigs.map(r => ({ name: r.name }))
});
}
/**
* +
*/
private async openUploadRepoSelect(folderId: string, folderType: 'git' | 'local'): Promise<void> {
await this.loadRepoConfigs();
2025-12-02 14:48:30 +08:00
if (this.repoConfigs.length === 0) {
vscode.window.showWarningMessage('尚未配置任何仓库,请先点击右上角 "仓库配置" 按钮编辑 dcsp-repos.json。');
return;
}
2025-12-02 14:48:30 +08:00
if (this.isWebviewDisposed) return;
this.panel.webview.postMessage({
type: 'showUploadRepoSelect',
repos: this.repoConfigs.map(r => ({ name: r.name })),
folderId,
folderType
});
}
/**
*
*/
private async handleRepoSelectedForBranches(repoName: string): Promise<void> {
await this.loadRepoConfigs();
const repo = this.repoConfigs.find(r => r.name === repoName);
2025-12-02 14:48:30 +08:00
if (!repo) {
vscode.window.showErrorMessage(`在仓库配置中未找到名为 "${repoName}" 的仓库`);
2025-12-03 16:08:14 +08:00
return;
}
2025-12-02 14:48:30 +08:00
2025-12-03 16:08:14 +08:00
this.currentRepoForBranches = repo;
await this.fetchBranchesForRepo(repo);
}
2025-12-02 12:52:41 +08:00
/**
* folderType 使 branchName
*/
private async handleUploadRepoSelected(
folderId: string,
folderType: 'git' | 'local',
repoName: string,
branchName: string
): Promise<void> {
const trimmedBranch = (branchName || '').trim();
if (!trimmedBranch) {
vscode.window.showErrorMessage('分支名称不能为空');
2025-12-03 16:08:14 +08:00
return;
}
await this.loadRepoConfigs();
const repo = this.repoConfigs.find(r => r.name === repoName);
if (!repo) {
vscode.window.showErrorMessage(`在仓库配置中未找到名为 "${repoName}" 的仓库`);
2025-12-03 16:08:14 +08:00
return;
}
if (folderType === 'local') {
// 本地模块 -> 选中仓库 + 指定分支
await this.uploadLocalModuleFolder(
folderId,
repo.url,
trimmedBranch,
repo.username,
repo.token
);
} else {
// Git 模块 -> 选中仓库 + 指定分支
await this.processGitUploadWithBranch(folderId, repo, trimmedBranch);
}
2025-12-03 16:08:14 +08:00
}
/**
* Git / 使
*/
private async processGitUploadWithBranch(
folderId: string,
repo: RepoConfigItem,
branchName: string
): Promise<void> {
2025-12-03 16:08:14 +08:00
const folder = this.projectService.getModuleFolder(folderId);
if (!folder || folder.type !== 'git') {
vscode.window.showErrorMessage("未找到要上传的 Git 模块文件夹");
return;
}
2025-12-03 16:08:14 +08:00
const newFolderName = folder.localPath.split('/').pop() ?? '';
const oldFolderName = folder.originalFolderName ?? newFolderName;
2025-12-03 16:08:14 +08:00
const isRenamed = newFolderName !== oldFolderName;
const isSameRepo = !!folder.originalRepoUrl && folder.originalRepoUrl === repo.url;
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (!fullPath) {
vscode.window.showErrorMessage("无法确定 Git 模块文件夹路径");
return;
}
// 未改名 + 还是原来的仓库 → 直接在原分支上 push更新代码
2025-12-03 16:08:14 +08:00
if (!isRenamed && isSameRepo) {
await this.uploadGitModuleFolder(folderId);
return;
}
2025-12-02 14:48:30 +08:00
// 改了名字 或 换了仓库 → 使用“用户输入的分支名”进行推送
2025-12-03 16:08:14 +08:00
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在上传 Git 仓库: ${folder.name}`,
cancellable: false
}, async (progress) => {
try {
progress.report({ increment: 0, message: '准备上传...' });
await GitService.pushToRepoUrl(
fullPath,
repo.url,
branchName,
2025-12-03 16:08:14 +08:00
repo.username,
repo.token
);
2025-12-03 16:08:14 +08:00
this.projectService.updateModuleFolder(folderId, {
uploaded: true,
originalFolderName: newFolderName,
originalRepoUrl: repo.url
});
2025-12-03 16:08:14 +08:00
await this.saveCurrentProjectData();
2025-12-03 16:08:14 +08:00
progress.report({ increment: 100, message: '完成' });
vscode.window.showInformationMessage(`✅ Git 仓库已上传到 ${repo.name} 的分支 ${branchName}`);
2025-12-03 16:08:14 +08:00
this.updateWebview();
} catch (error: any) {
console.error('❌ Git 上传到新仓库/分支失败:', error);
vscode.window.showErrorMessage(`推送失败: ${error.message || error}`);
}
});
}
2025-12-02 14:48:30 +08:00
// =============================================
// Webview 消息处理
// =============================================
2025-11-18 09:10:47 +08:00
private setupMessageListener() {
2025-11-21 16:07:48 +08:00
this.panel.webview.onDidReceiveMessage(async (data) => {
if (this.isWebviewDisposed) {
console.log('⚠️ Webview 已被销毁,忽略消息');
return;
}
try {
await this.handleWebviewMessage(data);
} catch (error) {
console.error('处理 Webview 消息时出错:', error);
if (!this.isWebviewDisposed) {
vscode.window.showErrorMessage(`处理操作时出错: ${error}`);
}
}
});
}
private async handleWebviewMessage(data: any): Promise<void> {
const messageHandlers: { [key: string]: (data: any) => Promise<void> } = {
// 导航相关
'openExistingProject': () => this.openExistingProject(),
'configureProject': (data) => this.handleConfigureProject(data),
'openProject': (data) => this.handleOpenProject(data),
'openAircraftConfig': (data) => this.handleOpenAircraftConfig(data),
'openContainerConfig': (data) => this.handleOpenContainerConfig(data),
'goBackToProjects': () => this.handleGoBackToProjects(),
'goBackToAircrafts': () => this.handleGoBackToAircrafts(),
'goBackToContainers': () => this.handleGoBackToContainers(),
// 项目管理
'updateProjectName': (data) => this.updateProjectName(data.projectId, data.name),
'createProject': (data) => this.createProject(data.name),
'deleteProject': (data) => this.deleteProject(data.projectId),
// 飞行器管理
'updateAircraftName': (data) => this.updateAircraftName(data.aircraftId, data.name),
'createAircraft': (data) => this.createAircraft(data.name),
'deleteAircraft': (data) => this.deleteAircraft(data.aircraftId),
// 容器管理
'updateContainerName': (data) => this.updateContainerName(data.containerId, data.name),
'createContainer': (data) => this.createContainer(data.name),
'deleteContainer': (data) => this.deleteContainer(data.containerId),
// 配置管理
'updateConfigName': (data) => this.updateConfigName(data.configId, data.name),
'createConfig': (data) => this.createConfig(data.name),
'deleteConfig': (data) => this.deleteConfig(data.configId),
'openConfigFileInVSCode': (data) => this.openConfigFileInVSCode(data.configId),
'mergeConfigs': (data) => this.mergeConfigs(data.configIds, data.displayName, data.folderName),
2025-12-03 16:08:14 +08:00
// Git 仓库管理
2025-12-02 12:52:41 +08:00
'openRepoConfig': () => this.openRepoConfig(),
'openRepoSelect': () => this.openRepoSelect(),
'repoSelectedForBranches': (data) => this.handleRepoSelectedForBranches(data.repoName),
2025-12-03 16:08:14 +08:00
// Git 分支管理
'fetchBranches': (data) => this.fetchBranches(data.url),
2025-12-02 12:52:41 +08:00
'cloneBranches': (data) => this.cloneBranches(data.branches),
'cancelBranchSelection': () => this.handleCancelBranchSelection(),
// 模块文件夹管理
'loadModuleFolder': (data) => this.loadModuleFolder(data.folderId),
'syncGitModuleFolder': (data) => this.syncGitModuleFolder(data.folderId),
'deleteModuleFolder': (data) => this.deleteModuleFolder(data.folderId),
'importGitFile': (data) => this.importGitFile(data.filePath),
'openTheModuleFolder': (data) => this.openTheModuleFolder(data.moduleType, data.id),
2025-12-02 14:48:30 +08:00
'renameModuleFolder': (data) => this.renameModuleFolder(data.folderId, data.newName),
// 上传功能
'uploadGitModuleFolder': (data) => this.uploadGitModuleFolder(data.folderId, data.username, data.password),
'openRepoSelectForUpload': (data) => this.openUploadRepoSelect(data.folderId, 'local'),
'uploadLocalModuleFolder': (data) => this.uploadLocalModuleFolder(data.folderId, data.repoUrl, data.branchName),
'openRepoSelectForGitUpload': (data) => this.openUploadRepoSelect(data.folderId, 'git'),
2025-12-04 10:16:57 +08:00
// 上传时 仓库+分支 选择确认
'uploadRepoSelected': (data) => this.handleUploadRepoSelected(
data.folderId,
data.folderType,
data.repoName,
data.branchName
)
};
const handler = messageHandlers[data.type];
if (handler) {
await handler(data);
} else {
console.warn(`未知的消息类型: ${data.type}`);
}
}
// =============================================
// 导航处理方法
// =============================================
private async handleConfigureProject(data: any): Promise<void> {
const selectedPath = await this.selectProjectPath(data.projectId, data.projectName);
if (selectedPath) {
this.currentView = 'aircrafts';
this.currentProjectId = data.projectId;
this.updateWebview();
}
}
private async handleOpenProject(data: any): Promise<void> {
this.currentView = 'aircrafts';
this.currentProjectId = data.projectId;
this.updateWebview();
}
private async handleOpenAircraftConfig(data: any): Promise<void> {
this.currentView = 'containers';
this.currentProjectId = data.projectId;
this.currentAircraftId = data.aircraftId;
this.updateWebview();
}
private async handleOpenContainerConfig(data: any): Promise<void> {
this.currentView = 'configs';
this.currentContainerId = data.containerId;
this.updateWebview();
}
private async handleGoBackToProjects(): Promise<void> {
this.currentView = 'projects';
this.currentProjectId = '';
this.currentAircraftId = '';
this.currentContainerId = '';
this.currentModuleFolderId = '';
this.updateWebview();
}
private async handleGoBackToAircrafts(): Promise<void> {
this.currentView = 'aircrafts';
this.currentAircraftId = '';
this.currentContainerId = '';
this.updateWebview();
}
private async handleGoBackToContainers(): Promise<void> {
this.currentView = 'containers';
this.currentContainerId = '';
this.updateWebview();
}
private async handleCancelBranchSelection(): Promise<void> {
console.log('❌ 取消分支选择');
this.updateWebview();
}
// =============================================
// 项目管理方法
// =============================================
private async updateProjectName(projectId: string, newName: string): Promise<void> {
2025-12-03 16:08:14 +08:00
if (this.projectService.updateProjectName(projectId, newName)) {
vscode.window.showInformationMessage(`项目名称更新: ${newName}`);
await this.saveCurrentProjectData();
this.updateWebview();
2025-11-28 14:16:19 +08:00
}
}
private async createProject(name: string): Promise<void> {
2025-12-03 16:08:14 +08:00
const newId = await this.projectService.createProject(name);
this.currentProjectId = newId;
vscode.window.showInformationMessage(`新建项目: ${name}`);
this.updateWebview();
}
private async deleteProject(projectId: string): Promise<void> {
2025-12-03 16:08:14 +08:00
if (this.projectService.deleteProject(projectId)) {
if (this.currentProjectId === projectId) {
this.currentProjectId = '';
this.currentView = 'projects';
}
vscode.window.showInformationMessage('项目已删除');
await this.saveCurrentProjectData();
this.updateWebview();
}
}
// =============================================
// 飞行器管理方法
// =============================================
private async updateAircraftName(aircraftId: string, newName: string): Promise<void> {
2025-12-03 16:08:14 +08:00
if (this.projectService.updateAircraftName(aircraftId, newName)) {
vscode.window.showInformationMessage(`飞行器名称更新: ${newName}`);
await this.saveCurrentProjectData();
this.updateWebview();
}
}
private async createAircraft(name: string): Promise<void> {
if (!this.currentProjectId) {
vscode.window.showErrorMessage('无法创建飞行器:未找到当前项目');
2025-11-28 14:16:19 +08:00
return;
}
2025-12-03 16:08:14 +08:00
const aircraftId = await this.projectService.createAircraft(name, this.currentProjectId);
vscode.window.showInformationMessage(`新建飞行器: ${name}`);
await this.saveCurrentProjectData();
this.updateWebview();
}
private async deleteAircraft(aircraftId: string): Promise<void> {
2025-12-03 16:08:14 +08:00
if (this.projectService.deleteAircraft(aircraftId)) {
vscode.window.showInformationMessage('飞行器已删除');
await this.saveCurrentProjectData();
this.updateWebview();
}
}
// =============================================
// 容器管理方法
// =============================================
private async updateContainerName(containerId: string, newName: string): Promise<void> {
2025-12-03 16:08:14 +08:00
if (this.projectService.updateContainerName(containerId, newName)) {
vscode.window.showInformationMessage(`容器名称更新: ${newName}`);
await this.saveCurrentProjectData();
this.updateWebview();
}
}
2025-11-28 14:16:19 +08:00
private async createContainer(name: string): Promise<void> {
if (!this.currentAircraftId) {
vscode.window.showErrorMessage('无法创建容器:未找到当前飞行器');
return;
}
2025-12-03 16:08:14 +08:00
const containerId = await this.projectService.createContainer(name, this.currentAircraftId);
vscode.window.showInformationMessage(`新建容器: ${name} (包含2个默认配置文件)`);
await this.saveCurrentProjectData();
this.updateWebview();
}
2025-11-25 21:13:41 +08:00
private async deleteContainer(containerId: string): Promise<void> {
2025-12-03 16:08:14 +08:00
if (this.projectService.deleteContainer(containerId)) {
vscode.window.showInformationMessage('容器已删除');
await this.saveCurrentProjectData();
this.updateWebview();
}
}
// =============================================
// 配置管理方法
// =============================================
2025-11-27 22:04:32 +08:00
private async updateConfigName(configId: string, newName: string): Promise<void> {
2025-12-03 16:08:14 +08:00
if (this.projectService.updateConfigName(configId, newName)) {
vscode.window.showInformationMessage(`配置名称更新: ${newName}`);
await this.saveCurrentProjectData();
this.updateWebview();
}
}
private async createConfig(name: string): Promise<void> {
2025-12-04 10:16:57 +08:00
// 注意:真正创建文件内容的逻辑放在 ProjectService.createConfig 里处理
2025-12-03 16:08:14 +08:00
const configId = await this.projectService.createConfig(name, this.currentContainerId);
vscode.window.showInformationMessage(`新建配置: ${name}`);
await this.saveCurrentProjectData();
this.updateWebview();
2025-11-18 09:10:47 +08:00
}
private async deleteConfig(configId: string): Promise<void> {
2025-12-03 16:08:14 +08:00
const config = this.projectService.getConfig(configId);
if (!config) return;
2025-11-25 21:13:41 +08:00
const confirm = await vscode.window.showWarningMessage(
`确定要删除配置文件 "${config.name}" 吗?这将同时删除磁盘上的文件。`,
2025-11-25 21:13:41 +08:00
{ modal: true },
'确定删除',
'取消'
);
if (confirm !== '确定删除') {
return;
}
2025-11-25 21:13:41 +08:00
try {
2025-12-04 10:16:57 +08:00
// 删除配置文件(磁盘)
2025-12-03 16:08:14 +08:00
await this.projectService.deleteConfigFileFromDisk(configId);
// 从内存中删除
this.projectService.deleteConfig(configId);
vscode.window.showInformationMessage(`删除配置: ${config.name}`);
await this.saveCurrentProjectData();
this.updateWebview();
2025-11-25 21:13:41 +08:00
} catch (error) {
vscode.window.showErrorMessage(`删除配置文件失败: ${error}`);
}
}
private async mergeConfigs(configIds: string[], displayName: string, folderName: string): Promise<void> {
if (!this.currentContainerId) {
vscode.window.showErrorMessage('未找到当前容器');
return;
}
if (configIds.length < 2) {
vscode.window.showErrorMessage('请至少选择两个配置文件进行合并');
return;
}
try {
2025-12-03 16:08:14 +08:00
const container = this.projectService.getContainersByAircraft(this.currentAircraftId)
.find(c => c.id === this.currentContainerId);
if (!container) {
vscode.window.showErrorMessage('未找到容器数据');
return;
}
2025-12-03 16:08:14 +08:00
const projectPath = this.projectService.getProjectPath(this.currentProjectId);
if (!projectPath) {
vscode.window.showErrorMessage('未找到项目路径');
return;
2025-11-27 22:04:32 +08:00
}
2025-12-04 10:16:57 +08:00
// 获取选中的配置(仅元信息,不含 content
2025-12-03 16:08:14 +08:00
const selectedConfigs = configIds
.map(id => this.projectService.getConfig(id))
.filter(Boolean);
if (selectedConfigs.length !== configIds.length) {
vscode.window.showErrorMessage('部分配置文件未找到');
return;
}
2025-12-03 16:08:14 +08:00
// 创建合并文件夹
const mergeFolderPath = path.join(projectPath, this.getAircraftName(), container.name, folderName);
await vscode.workspace.fs.createDirectory(vscode.Uri.file(mergeFolderPath));
2025-12-04 10:16:57 +08:00
const fs = require('fs');
// 复制文件到合并文件夹:完全基于磁盘文件
for (const config of selectedConfigs) {
2025-12-03 16:08:14 +08:00
if (!config) continue;
const sourcePath = this.projectService.getConfigFilePath(config.id);
const targetPath = path.join(mergeFolderPath, config.fileName);
2025-12-04 10:16:57 +08:00
if (sourcePath && fs.existsSync(sourcePath)) {
await fs.promises.copyFile(sourcePath, targetPath);
} else {
2025-12-04 10:16:57 +08:00
// 找不到源文件:写一个占位注释文件
const placeholder =
`# 原配置文件 "${config.fileName}" 未在磁盘中找到\n` +
`# 仅保留占位文件,建议手动补充内容\n\n`;
await fs.promises.writeFile(targetPath, placeholder, 'utf8');
}
}
2025-12-03 16:08:14 +08:00
// 创建模块文件夹记录(使用 ProjectService 的统一 ID 生成)
const relativePath = `/${this.currentProjectId}/${this.getAircraftName()}/${container.name}/${folderName}`;
const newFolder: ModuleFolder = {
2025-12-03 16:08:14 +08:00
id: this.projectService.generateUniqueId('local-'),
name: displayName,
type: 'local',
localPath: relativePath,
containerId: this.currentContainerId
};
2025-12-03 16:08:14 +08:00
this.projectService.addModuleFolder(newFolder);
2025-12-04 10:16:57 +08:00
// 删除原配置(包括磁盘上的配置文件)
for (const configId of configIds) {
2025-12-03 16:08:14 +08:00
await this.projectService.deleteConfigFileFromDisk(configId);
2025-12-04 10:16:57 +08:00
this.projectService.deleteConfig(configId);
}
await this.saveCurrentProjectData();
vscode.window.showInformationMessage(`成功合并 ${selectedConfigs.length} 个配置文件到文件夹: ${folderName}`);
this.updateWebview();
} catch (error) {
console.error('❌ 合并配置文件失败:', error);
vscode.window.showErrorMessage(`合并配置文件失败: ${error}`);
}
}
2025-12-03 16:08:14 +08:00
private getAircraftName(): string {
const aircrafts = this.projectService.getAircraftsByProject(this.currentProjectId);
const aircraft = aircrafts.find(a => a.id === this.currentAircraftId);
return aircraft?.name || '未知飞行器';
}
private getContainerName(): string {
const containers = this.projectService.getContainersByAircraft(this.currentAircraftId);
const container = containers.find(c => c.id === this.currentContainerId);
return container?.name || '未知容器';
}
// =============================================
// Git 分支管理方法
// =============================================
2025-12-02 12:52:41 +08:00
private async fetchBranchesForRepo(repo: RepoConfigItem): Promise<void> {
await this.fetchBranches(repo.url, repo);
}
private async fetchBranches(url: string, repo?: RepoConfigItem): Promise<void> {
try {
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: '正在获取分支信息',
cancellable: false
}, async (progress) => {
progress.report({ increment: 0, message: '连接远程仓库...' });
try {
progress.report({ increment: 30, message: '获取远程引用...' });
2025-12-02 12:52:41 +08:00
2025-12-03 16:08:14 +08:00
const branches = await GitService.fetchBranches(
url,
repo?.username,
repo?.token
);
if (branches.length === 0) {
throw new Error('未找到任何分支');
}
progress.report({ increment: 80, message: '处理分支数据...' });
2025-11-27 22:04:32 +08:00
2025-12-03 16:08:14 +08:00
const branchTree = GitService.buildBranchTree(branches);
if (!this.isWebviewDisposed) {
this.panel.webview.postMessage({
type: 'branchesFetched',
branches: branches,
branchTree: branchTree,
2025-12-02 12:52:41 +08:00
repoUrl: url,
repoName: repo?.name
});
}
progress.report({ increment: 100, message: '完成' });
} catch (error) {
2025-12-03 16:08:14 +08:00
console.error('❌ 获取分支失败:', error);
vscode.window.showErrorMessage(`获取分支失败: ${error}`);
}
});
} catch (error) {
console.error('❌ 获取分支失败:', error);
vscode.window.showErrorMessage(`获取分支失败: ${error}`);
}
}
2025-12-02 12:52:41 +08:00
private async cloneBranches(branches: string[]): Promise<void> {
if (!this.currentRepoForBranches) {
2025-12-03 16:08:14 +08:00
vscode.window.showErrorMessage('请先通过"获取仓库"选择一个仓库');
2025-12-02 12:52:41 +08:00
return;
}
const url = this.currentRepoForBranches.url;
const repoDisplayName = this.currentRepoForBranches.name;
2025-11-18 21:14:10 +08:00
try {
console.log('🚀 开始克隆分支:', { url, branches });
let successCount = 0;
let failCount = 0;
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}`);
try {
2025-12-03 16:08:14 +08:00
const folderNames = GitService.generateModuleFolderName(url, branch);
await this.addGitModuleFolder(
url,
repoDisplayName,
folderNames.folderName,
branch,
this.currentRepoForBranches?.username,
this.currentRepoForBranches?.token
);
2025-12-03 16:08:14 +08:00
successCount++;
console.log(`✅ 分支克隆成功: ${branch}`);
} catch (error) {
failCount++;
console.error(`❌ 分支克隆失败: ${branch}`, error);
}
}
2025-11-18 21:14:10 +08:00
});
if (failCount === 0) {
vscode.window.showInformationMessage(`成功克隆 ${successCount} 个分支`);
} else {
vscode.window.showWarningMessage(`克隆完成: ${successCount} 个成功, ${failCount} 个失败`);
2025-11-18 21:14:10 +08:00
}
2025-11-18 21:14:10 +08:00
} catch (error) {
console.error('❌ 克隆分支失败:', error);
vscode.window.showErrorMessage(`克隆分支失败: ${error}`);
2025-11-18 21:14:10 +08:00
}
}
2025-12-03 16:08:14 +08:00
private async addGitModuleFolder(
url: string,
displayName: string,
folderName: string,
branch?: string,
username?: string,
token?: string
): Promise<void> {
2025-11-27 22:04:32 +08:00
try {
if (!url || !url.startsWith('http')) {
vscode.window.showErrorMessage('请输入有效的 Git 仓库 URL');
2025-11-27 22:04:32 +08:00
return;
}
2025-11-21 16:07:48 +08:00
if (!this.currentContainerId) {
vscode.window.showErrorMessage('请先选择容器');
2025-11-27 22:04:32 +08:00
return;
}
2025-11-18 21:14:10 +08:00
2025-12-03 16:08:14 +08:00
const projectPath = this.projectService.getProjectPath(this.currentProjectId);
if (!projectPath) {
vscode.window.showErrorMessage('未找到相关项目数据');
return;
}
2025-11-18 21:14:10 +08:00
2025-12-03 16:08:14 +08:00
// 使用 ProjectService 的统一 ID 生成
const folderId = this.projectService.generateUniqueId('git-');
const relativePath = `/${this.currentProjectId}/${this.getAircraftName()}/${this.getContainerName()}/${folderName}`;
const localPath = path.join(projectPath, this.getAircraftName(), this.getContainerName(), folderName);
2025-11-27 22:04:32 +08:00
console.log(`📁 准备克隆仓库: ${displayName}, 分支: ${branch}, 路径: ${localPath}`);
2025-11-18 21:14:10 +08:00
2025-12-03 16:08:14 +08:00
const existingFolder = this.projectService.getModuleFoldersByContainer(this.currentContainerId)
.find(folder => folder.localPath === relativePath);
if (existingFolder) {
vscode.window.showWarningMessage(`该路径的模块文件夹已存在: ${folderName}`);
return;
2025-11-27 22:04:32 +08:00
}
2025-11-18 21:14:10 +08:00
const newFolder: ModuleFolder = {
id: folderId,
name: displayName,
type: 'git',
localPath: relativePath,
containerId: this.currentContainerId,
originalFolderName: folderName,
originalRepoUrl: url
};
2025-11-27 22:04:32 +08:00
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在克隆仓库: ${displayName}`,
cancellable: false
}, async (progress) => {
progress.report({ increment: 0 });
2025-11-18 21:14:10 +08:00
try {
2025-12-03 16:08:14 +08:00
// 使用 GitService 克隆仓库
await GitService.cloneRepository(
url,
localPath,
branch,
(event: any) => {
console.log(`📊 克隆进度: ${event.phase} - ${event.loaded}/${event.total}`);
if (event.total) {
const percent = (event.loaded / event.total) * 100;
progress.report({
increment: percent,
message: `${event.phase}... (${Math.round(percent)}%)`
});
} else {
progress.report({ message: `${event.phase}...` });
2025-11-18 21:14:10 +08:00
}
2025-12-03 16:08:14 +08:00
},
username,
token
);
2025-11-18 21:14:10 +08:00
console.log('✅ Git克隆成功完成');
2025-12-03 16:08:14 +08:00
const clonedContents = await require('fs').promises.readdir(localPath);
console.log(`📁 克隆后的目录内容:`, clonedContents);
2025-11-18 21:14:10 +08:00
if (clonedContents.length === 0) {
throw new Error('克隆后目录为空,可能克隆失败');
}
2025-12-03 16:08:14 +08:00
this.projectService.addModuleFolder(newFolder);
2025-11-21 16:07:48 +08:00
await this.saveCurrentProjectData();
console.log('✅ Git模块文件夹数据已保存到项目文件');
vscode.window.showInformationMessage(`Git 仓库克隆成功: ${displayName}`);
2025-11-18 21:14:10 +08:00
if (!this.isWebviewDisposed) {
console.log('🌳 开始加载模块文件夹文件树...');
this.currentModuleFolderId = folderId;
await this.loadModuleFolderFileTree(folderId);
console.log('✅ 模块文件夹文件树加载完成');
2025-11-18 14:03:22 +08:00
}
} catch (error) {
console.error('❌ 在克隆过程中捕获错误:', error);
2025-11-18 14:03:22 +08:00
try {
2025-12-03 16:08:14 +08:00
if (require('fs').existsSync(localPath)) {
await require('fs').promises.rm(localPath, { recursive: true, force: true });
console.log('🧹 已清理克隆失败的目录');
}
} catch (cleanupError) {
console.error('清理失败目录时出错:', cleanupError);
2025-11-18 14:03:22 +08:00
}
vscode.window.showErrorMessage(`克隆仓库失败: ${error}`);
throw error;
2025-11-18 14:03:22 +08:00
}
});
2025-11-18 14:03:22 +08:00
} catch (error) {
console.error('❌ 在addGitModuleFolder外部捕获错误:', error);
vscode.window.showErrorMessage(`添加 Git 模块文件夹失败: ${error}`);
2025-11-18 14:03:22 +08:00
}
}
2025-12-03 16:08:14 +08:00
// =============================================
// 模块文件夹管理方法
// =============================================
private async loadModuleFolder(folderId: string): Promise<void> {
this.currentModuleFolderId = folderId;
2025-12-03 16:08:14 +08:00
const folder = this.projectService.getModuleFolder(folderId);
if (folder && folder.type === 'git') {
await this.loadModuleFolderFileTree(folderId);
2025-11-18 09:10:47 +08:00
}
this.updateWebview();
}
private async syncGitModuleFolder(folderId: string): Promise<void> {
2025-12-03 16:08:14 +08:00
const folder = this.projectService.getModuleFolder(folderId);
if (!folder || folder.type !== 'git') {
vscode.window.showErrorMessage('未找到指定的 Git 模块文件夹');
return;
}
2025-11-18 18:45:30 +08:00
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (!fullPath) {
vscode.window.showErrorMessage('无法获取模块文件夹的完整路径');
return;
}
2025-11-18 14:03:22 +08:00
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在同步仓库: ${folder.name}`,
cancellable: false
}, async (progress) => {
try {
progress.report({ increment: 0, message: '拉取最新更改...' });
2025-12-03 16:08:14 +08:00
await GitService.pullChanges(fullPath);
await this.loadModuleFolderFileTree(folderId);
vscode.window.showInformationMessage(`Git 仓库同步成功: ${folder.name}`);
this.updateWebview();
} catch (error) {
vscode.window.showErrorMessage(`同步 Git 仓库失败: ${error}`);
}
});
2025-11-18 09:10:47 +08:00
}
private async deleteModuleFolder(folderId: string): Promise<void> {
2025-12-03 16:08:14 +08:00
const folder = this.projectService.getModuleFolder(folderId);
if (!folder) return;
const confirm = await vscode.window.showWarningMessage(
`确定要删除模块文件夹 "${folder.name}" 吗?这将删除本地文件。`,
{ modal: true },
'确定删除',
'取消'
);
if (confirm === '确定删除') {
try {
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (fullPath) {
2025-12-03 16:08:14 +08:00
await require('fs').promises.rm(fullPath, { recursive: true, force: true });
}
2025-12-03 16:08:14 +08:00
this.projectService.deleteModuleFolder(folderId);
await this.saveCurrentProjectData();
if (this.currentModuleFolderId === folderId) {
this.currentModuleFolderId = '';
this.currentModuleFolderFileTree = [];
}
vscode.window.showInformationMessage(`模块文件夹已删除: ${folder.name}`);
this.updateWebview();
} catch (error) {
vscode.window.showErrorMessage(`删除模块文件夹失败: ${error}`);
}
2025-11-18 18:45:30 +08:00
}
}
private async importGitFile(filePath: string): Promise<void> {
if (!this.currentModuleFolderId || !this.currentContainerId) {
vscode.window.showErrorMessage('请先选择模块文件夹和容器');
2025-11-18 18:45:30 +08:00
return;
}
2025-12-03 16:08:14 +08:00
const folder = this.projectService.getModuleFolder(this.currentModuleFolderId);
if (!folder || folder.type !== 'git') {
vscode.window.showErrorMessage('未找到当前 Git 模块文件夹');
return;
}
2025-11-25 09:24:31 +08:00
try {
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (!fullPath) {
vscode.window.showErrorMessage('无法获取模块文件夹路径');
return;
}
2025-11-18 18:45:30 +08:00
2025-12-04 10:16:57 +08:00
const fs = require('fs');
const sourceFullPath = path.join(fullPath, filePath);
const content = await fs.promises.readFile(sourceFullPath, 'utf8');
const fileName = path.basename(filePath);
2025-11-18 18:45:30 +08:00
2025-12-04 10:16:57 +08:00
// 1. 先创建一个配置ProjectService.createConfig 内部会在磁盘上生成文件)
2025-12-03 16:08:14 +08:00
const configId = await this.projectService.createConfig(fileName, this.currentContainerId);
2025-12-04 10:16:57 +08:00
// 2. 再把 Git 文件的内容写到该配置文件上,覆盖默认模板
const targetConfigPath = this.projectService.getConfigFilePath(configId);
if (!targetConfigPath) {
vscode.window.showErrorMessage('无法获取新配置文件的路径');
return;
2025-12-03 16:08:14 +08:00
}
2025-11-18 18:45:30 +08:00
2025-12-04 10:16:57 +08:00
const dirPath = path.dirname(targetConfigPath);
await fs.promises.mkdir(dirPath, { recursive: true });
await fs.promises.writeFile(targetConfigPath, content, 'utf8');
2025-11-21 16:07:48 +08:00
await this.saveCurrentProjectData();
2025-12-03 16:08:14 +08:00
vscode.window.showInformationMessage(`文件已导入: ${fileName}`);
2025-11-18 09:10:47 +08:00
this.updateWebview();
} catch (error) {
vscode.window.showErrorMessage(`导入文件失败: ${error}`);
2025-11-18 09:10:47 +08:00
}
}
// =============================================
// 上传功能方法
// =============================================
2025-12-02 12:52:41 +08:00
private async uploadGitModuleFolder(folderId: string, username?: string, password?: string): Promise<void> {
2025-12-03 16:08:14 +08:00
const folder = this.projectService.getModuleFolder(folderId);
if (!folder || folder.type !== 'git') {
vscode.window.showErrorMessage('未找到指定的 Git 模块文件夹');
2025-11-25 09:24:31 +08:00
return;
}
2025-11-18 09:10:47 +08:00
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (!fullPath) {
vscode.window.showErrorMessage('无法获取模块文件夹的完整路径');
return;
}
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在上传 Git 仓库: ${folder.name}`,
cancellable: false
}, async (progress) => {
try {
progress.report({ increment: 0, message: '检查更改...' });
2025-11-25 09:24:31 +08:00
2025-12-03 16:08:14 +08:00
await GitService.commitAndPush(fullPath);
progress.report({ increment: 100, message: '完成' });
2025-12-03 16:08:14 +08:00
this.projectService.updateModuleFolder(folderId, { uploaded: true });
await this.saveCurrentProjectData();
vscode.window.showInformationMessage(`✅ Git 仓库上传成功: ${folder.name}`);
this.updateWebview();
2025-12-02 12:52:41 +08:00
} catch (error: any) {
console.error('❌ Git 上传失败:', error);
2025-12-02 12:52:41 +08:00
vscode.window.showErrorMessage(`推送失败: ${error.message || error}`);
}
});
2025-11-18 09:10:47 +08:00
}
2025-12-03 16:08:14 +08:00
private async uploadLocalModuleFolder(
folderId: string,
repoUrl: string,
branchName: string,
username?: string,
token?: string
): Promise<void> {
const folder = this.projectService.getModuleFolder(folderId);
if (!folder || folder.type !== 'local') {
vscode.window.showErrorMessage('未找到指定的本地模块文件夹');
return;
}
2025-11-18 18:45:30 +08:00
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (!fullPath) {
vscode.window.showErrorMessage('无法获取模块文件夹的完整路径');
return;
}
2025-11-18 09:10:47 +08:00
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: `正在上传本地文件夹到 Git 仓库: ${folder.name}`,
cancellable: false
}, async (progress) => {
try {
progress.report({ increment: 0, message: '检查目录...' });
2025-11-18 09:10:47 +08:00
2025-12-04 10:16:57 +08:00
const fs = require('fs');
if (!fs.existsSync(fullPath)) {
throw new Error('本地文件夹不存在');
}
2025-11-18 09:10:47 +08:00
progress.report({ increment: 10, message: '初始化 Git 仓库...' });
2025-12-03 16:08:14 +08:00
await GitService.initRepository(fullPath, branchName);
2025-11-25 09:24:31 +08:00
progress.report({ increment: 20, message: '添加远程仓库...' });
await GitService.addRemote(fullPath, repoUrl, username, token);
2025-11-25 09:24:31 +08:00
progress.report({ increment: 40, message: '提交初始文件...' });
2025-12-03 16:08:14 +08:00
await GitService.commitInitialFiles(fullPath);
2025-11-18 09:10:47 +08:00
progress.report({ increment: 60, message: '推送到远程仓库...' });
2025-12-03 16:08:14 +08:00
await GitService.pushToRemote(fullPath, branchName);
progress.report({ increment: 100, message: '完成' });
2025-12-03 16:08:14 +08:00
this.projectService.updateModuleFolder(folderId, {
type: 'git',
uploaded: true,
originalFolderName: branchName,
originalRepoUrl: repoUrl
});
await this.saveCurrentProjectData();
vscode.window.showInformationMessage(`本地文件夹成功上传到 Git 仓库: ${folder.name} -> ${branchName}`);
this.updateWebview();
2025-12-02 12:52:41 +08:00
} catch (error: any) {
console.error('❌ 本地文件夹上传失败:', error);
2025-12-02 12:52:41 +08:00
vscode.window.showErrorMessage(`推送失败: ${error.message || error}`);
try {
const gitDir = path.join(fullPath, '.git');
2025-12-04 10:16:57 +08:00
const fs = require('fs');
if (fs.existsSync(gitDir)) {
await fs.promises.rm(gitDir, { recursive: true, force: true });
}
} catch (cleanupError) {
console.error('清理 .git 文件夹失败:', cleanupError);
}
}
});
}
// =============================================
2025-12-03 16:08:14 +08:00
// 文件树和模块文件夹方法
// =============================================
2025-12-03 16:08:14 +08:00
private async loadModuleFolderFileTree(folderId: string): Promise<void> {
if (this.isWebviewDisposed) {
console.log('⚠️ Webview 已被销毁,跳过文件树加载');
return;
}
2025-12-03 16:08:14 +08:00
const folder = this.projectService.getModuleFolder(folderId);
if (!folder) return;
try {
2025-12-03 16:08:14 +08:00
this.panel.webview.postMessage({
type: 'moduleFolderLoading',
loading: true
});
} catch (error) {
2025-12-03 16:08:14 +08:00
console.log('⚠️ 无法发送加载消息Webview 可能已被销毁');
return;
2025-11-18 09:10:47 +08:00
}
try {
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (fullPath) {
const fileTree = await GitService.buildFileTree(fullPath);
this.currentModuleFolderFileTree = fileTree;
}
2025-11-18 14:03:22 +08:00
} catch (error) {
2025-12-03 16:08:14 +08:00
console.error('加载模块文件夹文件树失败:', error);
this.currentModuleFolderFileTree = [];
}
2025-12-03 16:08:14 +08:00
if (this.isWebviewDisposed) {
console.log('⚠️ Webview 已被销毁,跳过完成通知');
return;
}
2025-12-03 16:08:14 +08:00
try {
this.panel.webview.postMessage({
type: 'moduleFolderLoading',
loading: false
});
2025-12-03 16:08:14 +08:00
this.updateWebview();
} catch (error) {
2025-12-03 16:08:14 +08:00
console.log('⚠️ 无法发送完成消息Webview 可能已被销毁');
}
}
2025-11-18 21:14:10 +08:00
2025-12-03 16:08:14 +08:00
private async openConfigFileInVSCode(configId: string): Promise<void> {
const config = this.projectService.getConfig(configId);
if (!config) {
vscode.window.showErrorMessage('未找到配置文件');
return;
}
2025-12-03 16:08:14 +08:00
const filePath = this.projectService.getConfigFilePath(configId);
if (!filePath) {
vscode.window.showErrorMessage('未设置项目存储路径');
return;
}
try {
2025-12-03 16:08:14 +08:00
const fs = require('fs');
if (!fs.existsSync(filePath)) {
vscode.window.showWarningMessage('配置文件不存在,将创建新文件');
const dirPath = path.dirname(filePath);
await fs.promises.mkdir(dirPath, { recursive: true });
2025-12-04 10:16:57 +08:00
const now = new Date();
const header =
`# ${config.fileName} 配置文件\n` +
`# 创建时间: ${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()} ` +
`${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}\n` +
`# 您可以在此编辑配置内容\n\n`;
await fs.promises.writeFile(filePath, header, 'utf8');
2025-12-03 16:08:14 +08:00
}
2025-12-03 16:08:14 +08:00
const document = await vscode.workspace.openTextDocument(filePath);
await vscode.window.showTextDocument(document);
} catch (error) {
2025-12-03 16:08:14 +08:00
vscode.window.showErrorMessage(`打开配置文件失败: ${error}`);
}
}
2025-12-03 16:08:14 +08:00
private async openTheModuleFolder(type: 'git' | 'local', id: string): Promise<void> {
const folder = this.projectService.getModuleFolder(id);
if (!folder) {
vscode.window.showErrorMessage('未找到指定的模块文件夹');
return;
}
try {
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
2025-12-04 10:16:57 +08:00
const fs = require('fs');
if (!fullPath || !fs.existsSync(fullPath)) {
2025-12-03 16:08:14 +08:00
vscode.window.showErrorMessage('模块文件夹目录不存在');
return;
}
2025-12-03 16:08:14 +08:00
const fileUri = await vscode.window.showOpenDialog({
defaultUri: vscode.Uri.file(fullPath),
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
openLabel: '选择要打开的文件',
title: `${folder.name} 中选择文件`
});
2025-12-03 16:08:14 +08:00
if (fileUri && fileUri.length > 0) {
const document = await vscode.workspace.openTextDocument(fileUri[0]);
await vscode.window.showTextDocument(document);
vscode.window.showInformationMessage(`已打开文件: ${path.basename(fileUri[0].fsPath)}`);
}
} catch (error) {
2025-12-03 16:08:14 +08:00
vscode.window.showErrorMessage(`打开模块文件夹文件失败: ${error}`);
}
}
2025-12-03 16:08:14 +08:00
private async renameModuleFolder(folderId: string, newName: string): Promise<void> {
const folder = this.projectService.getModuleFolder(folderId);
if (!folder) {
vscode.window.showErrorMessage('未找到模块文件夹');
return;
}
2025-12-03 16:08:14 +08:00
const oldName = folder.localPath.split('/').pop();
if (!oldName) return;
2025-12-03 16:08:14 +08:00
const fullPath = this.projectService.getModuleFolderFullPath(folder);
if (!fullPath) return;
2025-12-03 16:08:14 +08:00
const newFullPath = path.join(path.dirname(fullPath), newName);
2025-12-03 16:08:14 +08:00
try {
2025-12-04 10:16:57 +08:00
const fs = require('fs');
await fs.promises.rename(fullPath, newFullPath);
2025-12-03 16:08:14 +08:00
this.projectService.renameModuleFolder(folderId, newName);
await this.saveCurrentProjectData();
vscode.window.showInformationMessage(`已重命名文件夹: ${oldName}${newName}`);
this.updateWebview();
} catch (error) {
2025-12-03 16:08:14 +08:00
vscode.window.showErrorMessage('重命名失败: ' + error);
}
}
// =============================================
// 项目路径选择方法
// =============================================
private async openExistingProject(): Promise<void> {
try {
const result = await vscode.window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
openLabel: '选择项目文件夹',
title: '选择包含项目数据的文件夹'
});
if (result && result.length > 0) {
const selectedPath = result[0].fsPath;
await this.loadProjectData(selectedPath);
}
} catch (error) {
vscode.window.showErrorMessage(`打开项目时出错: ${error}`);
}
}
private async selectProjectPath(projectId: string, projectName: string): Promise<string | null> {
try {
const choice = await vscode.window.showQuickPick(
[
{
label: '$(folder) 选择现有文件夹',
description: '从文件系统中选择已存在的文件夹',
value: 'select'
},
{
label: '$(new-folder) 创建新文件夹',
description: '输入新文件夹路径(将自动创建)',
value: 'create'
2025-11-27 22:04:32 +08:00
}
],
{
placeHolder: '选择项目存储方式'
}
);
if (!choice) {
return null;
}
if (choice.value === 'select') {
return await this.selectExistingProjectPath(projectId, projectName);
} else {
return await this.createNewProjectPath(projectId, projectName);
}
} catch (error) {
vscode.window.showErrorMessage(`选择存储路径时出错: ${error}`);
return null;
}
}
2025-11-27 18:34:57 +08:00
private async selectExistingProjectPath(projectId: string, projectName: string): Promise<string | null> {
const result = await vscode.window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
openLabel: `选择 ${projectName} 的存储位置`,
title: `为项目 "${projectName}" 选择存储文件夹`
});
if (result && result.length > 0) {
const selectedPath = result[0].fsPath;
2025-12-03 16:08:14 +08:00
const hasExistingData = await StorageService.checkProjectPathHasData(selectedPath);
if (hasExistingData) {
const loadChoice = await vscode.window.showWarningMessage(
`在路径 ${selectedPath} 中检测到现有项目数据,是否加载?`,
{ modal: true },
'是,加载现有数据',
'否,创建新项目'
);
if (loadChoice === '是,加载现有数据') {
const success = await this.loadProjectData(selectedPath);
if (success) {
2025-12-03 16:08:14 +08:00
// loadProjectData 里已经设置好了 currentProjectId 和 projectPath
return selectedPath;
2025-11-27 22:04:32 +08:00
}
}
2025-12-03 16:08:14 +08:00
// 如果选择“否,创建新项目”,就往下走,覆盖旧数据
}
2025-12-03 16:08:14 +08:00
// 没有旧数据,或者选择了“创建新项目”,把当前 projectId 绑定到这个路径
this.projectService.setProjectPath(projectId, selectedPath);
vscode.window.showInformationMessage(`项目存储位置已设置: ${selectedPath}`);
await this.saveCurrentProjectData();
return selectedPath;
}
2025-12-03 16:08:14 +08:00
return null;
}
2025-11-27 18:34:57 +08:00
private async createNewProjectPath(projectId: string, projectName: string): Promise<string | null> {
const pathInput = await vscode.window.showInputBox({
prompt: '请输入项目存储路径(绝对路径)',
placeHolder: `/path/to/your/project/${projectName}`,
validateInput: (value) => {
if (!value) {
return '路径不能为空';
}
return null;
}
});
if (pathInput) {
try {
const dirUri = vscode.Uri.file(pathInput);
await vscode.workspace.fs.createDirectory(dirUri);
2025-12-03 16:08:14 +08:00
this.projectService.setProjectPath(projectId, pathInput);
vscode.window.showInformationMessage(`项目存储位置已创建: ${pathInput}`);
await this.saveCurrentProjectData();
return pathInput;
} catch (error) {
vscode.window.showErrorMessage(`创建目录失败: ${error}`);
return null;
}
}
return null;
}
2025-12-03 16:08:14 +08:00
private async loadProjectData(projectPath: string): Promise<boolean> {
try {
2025-12-03 16:08:14 +08:00
const projectId = await this.projectService.loadProjectData(projectPath);
if (projectId) {
this.currentProjectId = projectId;
this.currentView = 'aircrafts';
2025-12-03 16:08:14 +08:00
vscode.window.showInformationMessage(`项目数据已从 ${projectPath} 加载`);
this.updateWebview();
return true;
}
2025-12-03 16:08:14 +08:00
return false;
2025-11-27 22:04:32 +08:00
} catch (error) {
2025-12-03 16:08:14 +08:00
vscode.window.showErrorMessage(`加载项目数据失败: ${error}`);
return false;
2025-11-27 22:04:32 +08:00
}
}
2025-11-27 18:34:57 +08:00
// =============================================
2025-12-03 16:08:14 +08:00
// 数据持久化
// =============================================
2025-12-03 16:08:14 +08:00
private async saveCurrentProjectData(): Promise<void> {
if (!this.currentProjectId) {
console.warn('未找到当前项目,数据将不会保存');
return;
}
2025-12-02 14:48:30 +08:00
2025-12-03 16:08:14 +08:00
await this.projectService.saveCurrentProjectData(this.currentProjectId);
2025-12-02 14:48:30 +08:00
}
// =============================================
// Webview 更新方法
// =============================================
private updateWebview() {
if (this.isWebviewDisposed) {
console.log('⚠️ Webview 已被销毁,跳过更新');
return;
}
try {
this.panel.webview.html = this.getWebviewContent();
} catch (error) {
console.error('更新 Webview 失败:', error);
}
}
private getWebviewContent(): string {
switch (this.currentView) {
case 'projects':
return this.projectView.render({
2025-12-03 16:08:14 +08:00
projects: this.projectService.getProjects(),
projectPaths: this.projectService.getProjectPaths()
});
case 'aircrafts':
2025-12-03 16:08:14 +08:00
const projectAircrafts = this.projectService.getAircraftsByProject(this.currentProjectId);
return this.aircraftView.render({
aircrafts: projectAircrafts
});
case 'containers':
2025-12-03 16:08:14 +08:00
const project = this.projectService.getProjects().find(p => p.id === this.currentProjectId);
const currentAircraft = this.projectService.getAircraftsByProject(this.currentProjectId)
.find(a => a.id === this.currentAircraftId);
const projectContainers = this.projectService.getContainersByAircraft(this.currentAircraftId);
return this.containerView.render({
2025-12-03 16:08:14 +08:00
project: project,
aircraft: currentAircraft,
containers: projectContainers
});
case 'configs':
2025-12-03 16:08:14 +08:00
const currentContainer = this.projectService.getContainersByAircraft(this.currentAircraftId)
.find(c => c.id === this.currentContainerId);
const currentModuleFolder = this.projectService.getModuleFolder(this.currentModuleFolderId);
const containerConfigs = this.projectService.getConfigsByContainer(this.currentContainerId);
const containerModuleFolders = this.projectService.getModuleFoldersByContainer(this.currentContainerId);
return this.configView.render({
container: currentContainer,
configs: containerConfigs,
moduleFolders: containerModuleFolders,
currentModuleFolder: currentModuleFolder,
moduleFolderFileTree: this.currentModuleFolderFileTree,
moduleFolderLoading: false
});
default:
return this.projectView.render({
2025-12-03 16:08:14 +08:00
projects: this.projectService.getProjects(),
projectPaths: this.projectService.getProjectPaths()
});
}
}
}