0
0

打开git代码功能完成

This commit is contained in:
xubing
2025-11-25 21:13:41 +08:00
parent 23024a8461
commit 2577e3051b
7 changed files with 408 additions and 1093 deletions

View File

@@ -242,22 +242,10 @@ export class ConfigPanel {
await this.updateConfigName(data.configId, data.name);
break;
case 'updateConfigFileName':
await this.updateConfigFileName(data.configId, data.fileName);
break;
case 'createConfig':
await this.createConfig(data.name);
break;
case 'saveConfigFile':
await this.saveConfigFileToDisk(data.configId, data.content);
break;
case 'loadConfigFile':
this.loadConfigFile(data.configId);
break;
case 'deleteProject':
await this.deleteProject(data.projectId);
break;
@@ -309,6 +297,10 @@ export class ConfigPanel {
case 'openGitRepoInVSCode':
await this.openGitRepoInVSCode(data.repoId);
break;
case 'openConfigFileInVSCode':
await this.openConfigFileInVSCode(data.configId);
break;
}
} catch (error) {
console.error('处理 Webview 消息时出错:', error);
@@ -412,153 +404,153 @@ export class ConfigPanel {
* 添加 Git 仓库到容器目录
*/
private async addGitRepo(url: string, name: string, branch?: string): Promise<void> {
try {
// 验证 URL
if (!url || !url.startsWith('http')) {
vscode.window.showErrorMessage('请输入有效的 Git 仓库 URL');
return;
}
if (!this.currentContainerId) {
vscode.window.showErrorMessage('请先选择容器');
return;
}
const repoId = 'git-' + Date.now();
// 构建本地路径 - 在容器目录下创建分支子目录
const container = this.containers.find(c => c.id === this.currentContainerId);
if (!container) {
vscode.window.showErrorMessage('未找到容器');
return;
}
const aircraft = this.aircrafts.find(a => a.id === container.aircraftId);
if (!aircraft) {
vscode.window.showErrorMessage('未找到飞行器');
return;
}
const projectPath = this.projectPaths.get(aircraft.projectId);
if (!projectPath) {
vscode.window.showErrorMessage('未找到项目路径');
return;
}
// 为每个分支创建独立的子目录
const branchName = branch || 'main';
const branchSafeName = branchName.replace(/[^a-zA-Z0-9-_]/g, '-');
const repoDirName = `${name}-${branchSafeName}`;
// 路径:项目路径/飞行器名/容器名/仓库名-分支名/
const localPath = path.join(projectPath, aircraft.name, container.name, repoDirName);
console.log(`📁 Git仓库将保存到: ${localPath}`);
// 检查是否已存在相同 URL 和分支的仓库
const existingRepo = this.gitRepos.find(repo =>
repo.url === url && repo.branch === branchName && repo.containerId === this.currentContainerId
);
if (existingRepo) {
vscode.window.showWarningMessage('该 Git 仓库和分支组合已存在');
return;
}
const newRepo: GitRepo = {
id: repoId,
name: `${name} (${branchName})`, // 在名称中包含分支信息
url: url,
localPath: localPath,
branch: branchName,
lastSync: new Date().toLocaleString(),
containerId: this.currentContainerId
};
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(localPath, { recursive: true });
// 检查目录是否为空
const dirContents = await fs.promises.readdir(localPath);
if (dirContents.length > 0) {
const confirm = await vscode.window.showWarningMessage(
`目标目录不为空,确定要覆盖吗?`,
{ modal: true },
'确定覆盖',
'取消'
);
if (confirm !== '确定覆盖') {
vscode.window.showInformationMessage('克隆操作已取消');
return;
}
// 清空目录(除了 .git 文件夹,如果存在的话)
for (const item of dirContents) {
const itemPath = path.join(localPath, item);
if (item !== '.git') {
await fs.promises.rm(itemPath, { recursive: true, force: true });
}
}
}
// 克隆仓库
await git.clone({
fs: fs,
http: http,
dir: localPath,
url: url,
singleBranch: true,
depth: 1,
ref: branchName,
onProgress: (event: any) => {
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.saveCurrentProjectData();
console.log('✅ Git仓库数据已保存到项目文件');
vscode.window.showInformationMessage(`Git 仓库克隆成功: ${name} (${newRepo.branch})`);
// 检查 Webview 状态后再加载文件树
if (!this.isWebviewDisposed) {
console.log('🌳 开始加载仓库文件树...');
// 自动加载仓库文件树
this.currentRepoId = repoId;
await this.loadGitRepoFileTree(repoId);
console.log('✅ 仓库文件树加载完成');
} else {
console.log('⚠️ Webview 已被销毁,跳过文件树加载');
}
} catch (error) {
console.error('❌ 在克隆过程中捕获错误:', error);
vscode.window.showErrorMessage(`克隆仓库失败: ${error}`);
try {
// 验证 URL
if (!url || !url.startsWith('http')) {
vscode.window.showErrorMessage('请输入有效的 Git 仓库 URL');
return;
}
});
} catch (error) {
console.error('❌ 在addGitRepo外部捕获错误:', error);
vscode.window.showErrorMessage(`添加 Git 仓库失败: ${error}`);
if (!this.currentContainerId) {
vscode.window.showErrorMessage('请先选择容器');
return;
}
const repoId = 'git-' + Date.now();
// 构建本地路径 - 在容器目录下创建分支子目录
const container = this.containers.find(c => c.id === this.currentContainerId);
if (!container) {
vscode.window.showErrorMessage('未找到容器');
return;
}
const aircraft = this.aircrafts.find(a => a.id === container.aircraftId);
if (!aircraft) {
vscode.window.showErrorMessage('未找到飞行器');
return;
}
const projectPath = this.projectPaths.get(aircraft.projectId);
if (!projectPath) {
vscode.window.showErrorMessage('未找到项目路径');
return;
}
// 为每个分支创建独立的子目录
const branchName = branch || 'main';
const branchSafeName = branchName.replace(/[^a-zA-Z0-9-_]/g, '-');
const repoDirName = name;
// 路径:项目路径/飞行器名/容器名/仓库名-分支名/
const localPath = path.join(projectPath, aircraft.name, container.name, repoDirName);
console.log(`📁 Git仓库将保存到: ${localPath}`);
// 检查是否已存在相同 URL 和分支的仓库
const existingRepo = this.gitRepos.find(repo =>
repo.url === url && repo.branch === branchName && repo.containerId === this.currentContainerId
);
if (existingRepo) {
vscode.window.showWarningMessage('该 Git 仓库和分支组合已存在');
return;
}
const newRepo: GitRepo = {
id: repoId,
name: `${name} (${branchName})`, // 在名称中包含分支信息
url: url,
localPath: localPath,
branch: branchName,
lastSync: new Date().toLocaleString(),
containerId: this.currentContainerId
};
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(localPath, { recursive: true });
// 检查目录是否为空
const dirContents = await fs.promises.readdir(localPath);
if (dirContents.length > 0) {
const confirm = await vscode.window.showWarningMessage(
`目标目录不为空,确定要覆盖吗?`,
{ modal: true },
'确定覆盖',
'取消'
);
if (confirm !== '确定覆盖') {
vscode.window.showInformationMessage('克隆操作已取消');
return;
}
// 清空目录(除了 .git 文件夹,如果存在的话)
for (const item of dirContents) {
const itemPath = path.join(localPath, item);
if (item !== '.git') {
await fs.promises.rm(itemPath, { recursive: true, force: true });
}
}
}
// 克隆仓库
await git.clone({
fs: fs,
http: http,
dir: localPath,
url: url,
singleBranch: true,
depth: 1,
ref: branchName,
onProgress: (event: any) => {
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.saveCurrentProjectData();
console.log('✅ Git仓库数据已保存到项目文件');
vscode.window.showInformationMessage(`Git 仓库克隆成功: ${name} (${newRepo.branch})`);
// 检查 Webview 状态后再加载文件树
if (!this.isWebviewDisposed) {
console.log('🌳 开始加载仓库文件树...');
// 自动加载仓库文件树
this.currentRepoId = repoId;
await this.loadGitRepoFileTree(repoId);
console.log('✅ 仓库文件树加载完成');
} else {
console.log('⚠️ Webview 已被销毁,跳过文件树加载');
}
} catch (error) {
console.error('❌ 在克隆过程中捕获错误:', error);
vscode.window.showErrorMessage(`克隆仓库失败: ${error}`);
}
});
} catch (error) {
console.error('❌ 在addGitRepo外部捕获错误:', error);
vscode.window.showErrorMessage(`添加 Git 仓库失败: ${error}`);
}
}
}
/**
* 加载 Git 仓库文件树
@@ -613,42 +605,42 @@ export class ConfigPanel {
}
/**
* 删除 Git 仓库
*/
private async deleteGitRepo(repoId: string): Promise<void> {
const repo = this.gitRepos.find(r => r.id === repoId);
if (!repo) return;
* 删除 Git 仓库
*/
private async deleteGitRepo(repoId: string): Promise<void> {
const repo = this.gitRepos.find(r => r.id === repoId);
if (!repo) return;
const confirm = await vscode.window.showWarningMessage(
`确定要删除 Git 仓库 "${repo.name}" 吗?这将删除本地文件。`,
{ modal: true },
'确定删除',
'取消'
);
const confirm = await vscode.window.showWarningMessage(
`确定要删除 Git 仓库 "${repo.name}" 吗?这将删除本地文件。`,
{ modal: true },
'确定删除',
'取消'
);
if (confirm === '确定删除') {
try {
// 删除整个仓库目录(因为是独立目录)
await fs.promises.rm(repo.localPath, { recursive: true, force: 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.saveCurrentProjectData();
// 从列表中移除
this.gitRepos = this.gitRepos.filter(r => r.id !== repoId);
await this.saveCurrentProjectData();
// 如果删除的是当前仓库,清空状态
if (this.currentRepoId === repoId) {
this.currentRepoId = '';
this.currentRepoFileTree = [];
// 如果删除的是当前仓库,清空状态
if (this.currentRepoId === repoId) {
this.currentRepoId = '';
this.currentRepoFileTree = [];
}
vscode.window.showInformationMessage(`Git 仓库已删除: ${repo.name}`);
this.updateWebview();
} catch (error) {
vscode.window.showErrorMessage(`删除 Git 仓库失败: ${error}`);
}
vscode.window.showInformationMessage(`Git 仓库已删除: ${repo.name}`);
this.updateWebview();
} catch (error) {
vscode.window.showErrorMessage(`删除 Git 仓库失败: ${error}`);
}
}
}
/**
* 加载 Git 仓库文件树
@@ -1238,17 +1230,6 @@ private async deleteGitRepo(repoId: string): Promise<void> {
}
}
// 更新文件名
private async updateConfigFileName(configId: string, fileName: string): Promise<void> {
const config = this.configs.find(c => c.id === configId);
if (config) {
config.fileName = fileName;
vscode.window.showInformationMessage(`文件名更新: ${fileName}`);
await this.saveCurrentProjectData();
this.updateWebview();
}
}
// 创建新配置文件
private async createConfig(name: string) {
const newId = 'cfg' + (this.configs.length + 1);
@@ -1316,207 +1297,108 @@ private async deleteGitRepo(repoId: string): Promise<void> {
}
}
// 保存配置文件到磁盘
private async saveConfigFileToDisk(configId: string, content: string): Promise<void> {
try {
const config = this.configs.find(c => c.id === configId);
if (!config) {
vscode.window.showErrorMessage('未找到配置文件');
return;
}
const container = this.containers.find(c => c.id === config.containerId);
if (!container) {
vscode.window.showErrorMessage('未找到容器');
return;
}
const aircraft = this.aircrafts.find(a => a.id === container.aircraftId);
if (!aircraft) {
vscode.window.showErrorMessage('未找到飞行器');
return;
}
const project = this.projects.find(p => p.id === aircraft.projectId);
if (!project) {
vscode.window.showErrorMessage('未找到项目');
return;
}
const projectPath = this.projectPaths.get(aircraft.projectId);
if (!projectPath) {
vscode.window.showErrorMessage('未设置项目存储路径,请先配置项目');
return;
}
// 构建文件路径:项目路径/飞行器名/容器名/文件名
const aircraftDir = vscode.Uri.joinPath(vscode.Uri.file(projectPath), aircraft.name);
const containerDir = vscode.Uri.joinPath(aircraftDir, container.name);
const fileUri = vscode.Uri.joinPath(containerDir, config.fileName);
// 确保飞行器目录存在
try {
await vscode.workspace.fs.createDirectory(aircraftDir);
} catch (error) {
// 目录可能已存在,忽略错误
}
// 确保容器目录存在
try {
await vscode.workspace.fs.createDirectory(containerDir);
} catch (error) {
// 目录可能已存在,忽略错误
}
// 写入文件
const uint8Array = new TextEncoder().encode(content);
await vscode.workspace.fs.writeFile(fileUri, uint8Array);
// 更新配置内容
config.content = content;
vscode.window.showInformationMessage(`配置文件已保存: ${fileUri.fsPath}`);
// 保存数据到JSON文件
await this.saveCurrentProjectData();
} catch (error) {
vscode.window.showErrorMessage(`保存文件时出错: ${error}`);
}
}
// 加载配置文件
private loadConfigFile(configId: string) {
if (this.isWebviewDisposed) {
console.log('⚠️ Webview 已被销毁,跳过加载配置文件');
return;
}
const config = this.configs.find(c => c.id === configId);
if (config) {
try {
this.panel.webview.postMessage({
type: 'configFileLoaded',
content: config.content || `# ${config.name} 的配置文件\n# 您可以在此编辑配置内容\n\n`
});
} catch (error) {
console.log('⚠️ 无法发送配置文件内容Webview 可能已被销毁');
}
} else {
try {
this.panel.webview.postMessage({
type: 'configFileLoaded',
content: `# 这是 ${configId} 的配置文件\n# 您可以在此编辑配置内容\n\napp.name = "示例应用"\napp.port = 8080\napp.debug = true`
});
} catch (error) {
console.log('⚠️ 无法发送默认配置文件内容Webview 可能已被销毁');
}
}
}
// === Git 分支管理 ===
private async fetchBranches(url: string): Promise<void> {
try {
console.log('🌿 开始获取分支列表:', url);
await vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: '正在获取分支信息',
cancellable: false
}, async (progress) => {
progress.report({ increment: 0, message: '连接远程仓库...' });
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 git.listServerRefs({
http: http,
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: GitBranch[] = branchRefs.map(ref => {
const isRemote = ref.ref.startsWith('refs/remotes/');
let branchName: string;
try {
// 使用 isomorphic-git 的 listServerRefs
progress.report({ increment: 30, message: '获取远程引用...' });
if (isRemote) {
// 远程分支:移除 refs/remotes/origin/ 前缀
branchName = ref.ref.replace('refs/remotes/origin/', '');
// 可以选择添加远程标识,或者不添加
// branchName = `origin/${branchName}`; // 如果需要显示远程标识
} else {
// 本地分支:移除 refs/heads/ 前缀
branchName = ref.ref.replace('refs/heads/', '');
console.log('🔍 使用 listServerRefs 获取分支信息...');
const refs = await git.listServerRefs({
http: http,
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: GitBranch[] = branchRefs.map(ref => {
const isRemote = ref.ref.startsWith('refs/remotes/');
let branchName: string;
if (isRemote) {
// 远程分支:移除 refs/remotes/origin/ 前缀
branchName = ref.ref.replace('refs/remotes/origin/', '');
} else {
// 本地分支:移除 refs/heads/ 前缀
branchName = ref.ref.replace('refs/heads/', '');
}
return {
name: branchName,
isCurrent: branchName === 'main' || branchName === 'master',
isRemote: isRemote,
selected: false // 所有分支默认不选中
};
});
console.log('🎯 最终分支列表:', branches);
if (branches.length === 0) {
throw new Error('未找到任何分支');
}
progress.report({ increment: 80, message: '处理分支数据...' });
// 发送分支数据到前端
if (!this.isWebviewDisposed) {
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: false },
{ 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 }
];
if (!this.isWebviewDisposed) {
this.panel.webview.postMessage({
type: 'branchesFetched',
branches: mockBranches,
repoUrl: url
});
}
return {
name: branchName,
isCurrent: branchName === 'main' || branchName === 'master',
isRemote: isRemote,
selected: false // 所有分支默认不选中
};
});
console.log('🎯 最终分支列表:', branches);
if (branches.length === 0) {
throw new Error('未找到任何分支');
vscode.window.showWarningMessage('使用模拟分支数据,实际分支可能不同');
}
});
progress.report({ increment: 80, message: '处理分支数据...' });
// 发送分支数据到前端
if (!this.isWebviewDisposed) {
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: false },
{ 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 }
];
if (!this.isWebviewDisposed) {
this.panel.webview.postMessage({
type: 'branchesFetched',
branches: mockBranches,
repoUrl: url
});
}
vscode.window.showWarningMessage('使用模拟分支数据,实际分支可能不同');
}
});
} catch (error) {
console.error('❌ 获取分支失败:', error);
vscode.window.showErrorMessage(`获取分支失败: ${error}`);
} catch (error) {
console.error('❌ 获取分支失败:', error);
vscode.window.showErrorMessage(`获取分支失败: ${error}`);
}
}
}
private async cloneBranches(url: string, branches: string[]): Promise<void> {
try {
@@ -1550,10 +1432,10 @@ private async deleteGitRepo(repoId: string): Promise<void> {
}
private generateRepoName(url: string, branch: string): string {
const repoName = url.split('/').pop()?.replace('.git', '') || 'unknown-repo';
const branchSafeName = branch.replace(/[^a-zA-Z0-9-_]/g, '-');
return `${repoName}-${branchSafeName}`;
}
const repoName = url.split('/').pop()?.replace('.git', '') || 'unknown-repo';
const branchSafeName = branch.replace(/[^a-zA-Z0-9-_]/g, '-');
return `${repoName}-${branchSafeName}`;
}
// 更新视图
private updateWebview() {
@@ -1615,39 +1497,88 @@ private async deleteGitRepo(repoId: string): Promise<void> {
});
}
}
private async openGitRepoInVSCode(repoId: string): Promise<void> {
const repo = this.gitRepos.find(r => r.id === repoId);
if (!repo) {
vscode.window.showErrorMessage('未找到指定的 Git 仓库');
return;
}
try {
// 检查仓库目录是否存在
if (!fs.existsSync(repo.localPath)) {
vscode.window.showErrorMessage('Git 仓库目录不存在,请重新克隆');
private async openGitRepoInVSCode(repoId: string): Promise<void> {
const repo = this.gitRepos.find(r => r.id === repoId);
if (!repo) {
vscode.window.showErrorMessage('未找到指定的 Git 仓库');
return;
}
// 使用 VSCode 的文件选择器让用户选择要打开的文件
const fileUri = await vscode.window.showOpenDialog({
defaultUri: vscode.Uri.file(repo.localPath),
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
openLabel: '选择要打开的文件',
title: `${repo.name} 中选择文件`
});
try {
// 检查仓库目录是否存在
if (!fs.existsSync(repo.localPath)) {
vscode.window.showErrorMessage('Git 仓库目录不存在,请重新克隆');
return;
}
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)}`);
// 使用 VSCode 的文件选择器让用户选择要打开的文件
const fileUri = await vscode.window.showOpenDialog({
defaultUri: vscode.Uri.file(repo.localPath),
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
openLabel: '选择要打开的文件',
title: `${repo.name} 中选择文件`
});
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) {
vscode.window.showErrorMessage(`打开 Git 仓库文件失败: ${error}`);
}
}
private async openConfigFileInVSCode(configId: string): Promise<void> {
const config = this.configs.find(c => c.id === configId);
if (!config) {
vscode.window.showErrorMessage('未找到配置文件');
return;
}
} catch (error) {
vscode.window.showErrorMessage(`打开 Git 仓库文件失败: ${error}`);
const container = this.containers.find(c => c.id === config.containerId);
if (!container) {
vscode.window.showErrorMessage('未找到容器');
return;
}
const aircraft = this.aircrafts.find(a => a.id === container.aircraftId);
if (!aircraft) {
vscode.window.showErrorMessage('未找到飞行器');
return;
}
const projectPath = this.projectPaths.get(aircraft.projectId);
if (!projectPath) {
vscode.window.showErrorMessage('未设置项目存储路径');
return;
}
// 构建文件路径
const filePath = path.join(projectPath, aircraft.name, container.name, config.fileName);
try {
// 检查文件是否存在
if (!fs.existsSync(filePath)) {
vscode.window.showWarningMessage('配置文件不存在,将创建新文件');
// 确保目录存在
const dirPath = path.dirname(filePath);
await fs.promises.mkdir(dirPath, { recursive: true });
// 创建文件
await fs.promises.writeFile(filePath, config.content || '');
}
// 在 VSCode 中打开文件
const document = await vscode.workspace.openTextDocument(filePath);
await vscode.window.showTextDocument(document);
} catch (error) {
vscode.window.showErrorMessage(`打开配置文件失败: ${error}`);
}
}
}
}