diff --git a/plugins/openidea-plugin/.gitignore b/plugins/openidea-plugin/.gitignore new file mode 100644 index 000000000..2157a49e2 --- /dev/null +++ b/plugins/openidea-plugin/.gitignore @@ -0,0 +1,8 @@ +node_modules/ +.DS_Store +*.log +.codebuddy/ + +# 仅用于本地开发,不进入插件发布包 +AGENTS.md +package-lock.json diff --git a/plugins/openidea-plugin/CHANGELOG.md b/plugins/openidea-plugin/CHANGELOG.md new file mode 100644 index 000000000..e4baa6840 --- /dev/null +++ b/plugins/openidea-plugin/CHANGELOG.md @@ -0,0 +1,15 @@ +## 1.0.0 - 2026-12-03 + +### 新增 + +- 读取 OpenIDEA 最近项目列表(recent.json),按打开时间倒序展示 +- 支持项目名、路径、分支的模糊搜索(多关键词同时匹配) +- 支持项目分组标签:读取 recent-groups.json,副标题展示 [组名],组名可参与搜索 +- 调用 OpenIDEA 自带 CLI 打开项目,复用已运行实例 +- 支持 macOS 与 Windows(含官方 openidea.cmd 包装脚本与 PATH 兜底) + +### 修复 + +- 缺失判定对齐官方口径:远程路径与 WSL 共享目录不再误判为目录缺失 +- 分支从 .git/HEAD 实时读取,兼容 worktree 与 detached HEAD +- 缺失目录与远程项目在启动前拦截并提示,不再透出 CLI 英文报错 diff --git a/plugins/openidea-plugin/LICENSE b/plugins/openidea-plugin/LICENSE new file mode 100644 index 000000000..e13051e6f --- /dev/null +++ b/plugins/openidea-plugin/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 zl + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/plugins/openidea-plugin/README.md b/plugins/openidea-plugin/README.md new file mode 100644 index 000000000..d1f26c38e --- /dev/null +++ b/plugins/openidea-plugin/README.md @@ -0,0 +1,54 @@ +# openidea-plugin + +> A ZTools plugin + +一个 ZTools 插件:快速打开 OpenIDEA 的最近项目。 + +## 功能 + +- 读取 `ai.l0ng.openidea` 的最近项目记录,按打开时间倒序展示 +- 支持项目名 / 路径 / 分支模糊搜索(空格分隔多关键词) +- 分支实时读取 `.git/HEAD`,切换分支后无需重开项目 +- 一键在 OpenIDEA 中打开项目,复用已运行实例 +- 支持项目分组标签:读取 `recent-groups.json`,副标题显示 `[组名]`,组名也可搜索 +- 目录已不存在的项目标注 `[目录缺失]`,远程项目标注 `[远程]` + +## 数据来源 + +| 平台 | 路径 | +|---|---| +| macOS | `~/Library/Application Support/ai.l0ng.openidea/recent.json` | +| Windows | `%APPDATA%\ai.l0ng.openidea\recent.json` | + +字段:`path`、`name`、`openedAtMs`、`branch`、`missing`。其中 `branch` 与 `missing` 是上次展示时的快照,插件会重新计算。 + +同目录下的 `recent-groups.json`(可选)保存项目分组,插件只读取 `name` 与 `paths` 做标签展示,不改变排序。 + +## 启动方式 + +- macOS:`OpenIDEA.app/Contents/Resources/bin/openidea ` +- Windows:`openidea.exe --cli `,或解析官方 `%LOCALAPPDATA%\OpenIDEA\bin\openidea.cmd` 包装脚本 + +## 开发 + +```bash +npm install +``` + +无构建步骤,把本目录作为本地插件导入 ZTools 开发模式即可调试。 + +## 结构 + +- `preload.js`:入口,导出 `window.exports`(列表模式) +- `service/features.js`:enter / search / select,列表组装与搜索 +- `service/init_service.js`:读取 recent.json +- `utils/launcher.js`:定位 OpenIDEA 并调用其 CLI 打开项目 +- `utils/project_path.js`:远程/缺失判定与实时分支读取 + +## 参考 + +上游实现:https://github.com/l0ng-ai/openidea + +## License + +MIT diff --git a/plugins/openidea-plugin/logo.png b/plugins/openidea-plugin/logo.png new file mode 100644 index 000000000..ee49a62c1 Binary files /dev/null and b/plugins/openidea-plugin/logo.png differ diff --git a/plugins/openidea-plugin/package.json b/plugins/openidea-plugin/package.json new file mode 100644 index 000000000..37278ed6e --- /dev/null +++ b/plugins/openidea-plugin/package.json @@ -0,0 +1,11 @@ +{ + "name": "openidea-plugin", + "version": "1.0.0", + "description": "打开 OpenIDEA 最近项目,支持模糊搜索与一键启动", + "author": "zl", + "license": "MIT", + "type": "commonjs", + "devDependencies": { + "@ztools-center/ztools-api-types": "^1.0.1" + } +} diff --git a/plugins/openidea-plugin/plugin.json b/plugins/openidea-plugin/plugin.json new file mode 100644 index 000000000..00f5d563b --- /dev/null +++ b/plugins/openidea-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "$schema": "node_modules/@ztools-center/ztools-api-types/resource/ztools.schema.json", + "name": "openidea-plugin", + "title": "OpenIDEA 最近项目", + "description": "打开 OpenIDEA 最近项目,支持模糊搜索与一键启动", + "author": "zl", + "version": "1.0.0", + "platform": ["darwin", "win32"], + "preload": "preload.js", + "logo": "logo.png", + "features": [ + { + "code": "all", + "explain": "快速打开 OpenIDEA 最近项目", + "cmds": ["OpenIDEA", "OI", "OID", "oo"] + } + ] +} diff --git a/plugins/openidea-plugin/preload.js b/plugins/openidea-plugin/preload.js new file mode 100644 index 000000000..5ab47041f --- /dev/null +++ b/plugins/openidea-plugin/preload.js @@ -0,0 +1,13 @@ +// ZTools Preload Script window.ztools +// 运行在 Node.js 环境,可以使用 Node.js API +const features = require("./service/features") + +// 监听插件进入事件 +window.ztools.onPluginEnter(({ code, type, payload }) => { + console.info('Plugin entered:', code, type, payload) +}); + +// ztools 选项列表 +window.exports = { + ...features.features +} diff --git a/plugins/openidea-plugin/service/features.js b/plugins/openidea-plugin/service/features.js new file mode 100644 index 000000000..28f80c625 --- /dev/null +++ b/plugins/openidea-plugin/service/features.js @@ -0,0 +1,137 @@ +const { initService } = require("./init_service"); +const { launchProject } = require("../utils/launcher"); + +/** + * 搜索项目 + * @param searchWord 搜索词(空格分隔多关键词,需全部命中) + * @returns 项目列表 + */ +function search(searchWord) { + const keywordList = String(searchWord || "") + .toLowerCase() + .split(/\s+/) + .filter(Boolean); + + if (!keywordList.length) { + return initService.projects.map(buildListItem); + } + + return initService.projects + .filter((project) => { + // 项目名、路径、分支都参与匹配,方便按目录或分支快速定位 + const haystack = ( + project.name + " " + project.path + " " + project.branch + " " + project.group + ).toLowerCase(); + return keywordList.every((keyword) => haystack.includes(keyword)); + }) + .map(buildListItem); +} + +/** + * 组装列表项(宿主列表模式只渲染 title / description / icon) + * @param project 项目数据 + * @returns 列表项 + */ +function buildListItem(project) { + const descriptionParts = []; + // 分组标签放最前,便于在长列表里按组扫读 + if (project.group) { + descriptionParts.push("[" + project.group + "]"); + } + if (project.remote) { + descriptionParts.push("[远程]"); + } else if (project.missing) { + descriptionParts.push("[目录缺失]"); + } + descriptionParts.push(project.path); + if (project.branch) { + descriptionParts.push(project.branch); + } + const openedAtText = formatOpenedAt(project.openedAtMs); + if (openedAtText) { + descriptionParts.push(openedAtText); + } + + return { + title: project.name, + description: descriptionParts.join(" · "), + icon: initService.app ? initService.app.icon : "", + // 以下字段供 select 使用,不影响列表渲染 + path: project.path, + branch: project.branch, + missing: project.missing, + remote: project.remote + }; +} + +/** + * 打开时间格式化:今天/昨天只显示时分,今年省略年份 + * @param openedAtMs 打开时间戳(毫秒) + * @returns 展示文本;无效时间返回空串 + */ +function formatOpenedAt(openedAtMs) { + const date = new Date(openedAtMs); + if (!openedAtMs || Number.isNaN(date.getTime())) { + return ""; + } + const now = new Date(); + const pad = (value) => String(value).padStart(2, "0"); + const timeText = pad(date.getHours()) + ":" + pad(date.getMinutes()); + + const isSameDay = + date.getFullYear() === now.getFullYear() && + date.getMonth() === now.getMonth() && + date.getDate() === now.getDate(); + if (isSameDay) { + return "今天 " + timeText; + } + + const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1); + const isYesterday = + date.getFullYear() === yesterday.getFullYear() && + date.getMonth() === yesterday.getMonth() && + date.getDate() === yesterday.getDate(); + if (isYesterday) { + return "昨天 " + timeText; + } + + const monthDay = pad(date.getMonth() + 1) + "-" + pad(date.getDate()); + if (date.getFullYear() === now.getFullYear()) { + return monthDay + " " + timeText; + } + return date.getFullYear() + "-" + monthDay; +} + +exports.features = { + all: { + mode: "list", + args: { + // 进入插件应用时调用 + enter: (action, callbackSetList) => { + if (window.ztools.isDev() && window.ztools.zbrowser) { + window.ztools.zbrowser.devTools("undocked"); + } + try { + initService.init(); + } catch (error) { + // 初始化失败也要回调,避免插件空白 + console.error("init failed:", error && error.message); + } + callbackSetList(search("")); + }, + search: (action, searchWord, callbackSetList) => { + callbackSetList(search(searchWord)); + }, + select: (action, itemData) => { + const projectPath = itemData && typeof itemData.path === "string" ? itemData.path : ""; + window.ztools.hideMainWindow(); + launchProject(projectPath); + window.ztools.outPlugin(); + }, + placeholder: "搜索 OpenIDEA 最近项目(名称 / 路径 / 分支)" + } + } +}; + +exports.search = search; +exports.formatOpenedAt = formatOpenedAt; diff --git a/plugins/openidea-plugin/service/init_service.js b/plugins/openidea-plugin/service/init_service.js new file mode 100644 index 000000000..17ecdf3b7 --- /dev/null +++ b/plugins/openidea-plugin/service/init_service.js @@ -0,0 +1,176 @@ +const fs = require("fs"); +const path = require("path"); +const { resolveApp } = require("../utils/launcher"); +const { isMissing, isRemotePath, readLiveBranch } = require("../utils/project_path"); + +// 配置目录名即应用 bundle id(Tauri 的 app_config_dir 规则): +// macOS 为 ~/Library/Application Support,Windows 为 %APPDATA% +const CONFIG_DIR_NAME = "ai.l0ng.openidea"; +const RECENT_FILE_NAME = "recent.json"; +const RECENT_GROUPS_FILE_NAME = "recent-groups.json"; + +/** + * 初始化服务:定位 OpenIDEA 安装位置、读取最近项目 + */ +class InitService { + // OpenIDEA 应用信息(安装路径 / CLI / 图标) + app = null; + + // 最近项目列表(已按打开时间倒序) + projects = []; + + /** + * 初始化入口:每次进入插件都重新读取,保证刚打开过的项目立刻出现在列表里 + */ + init() { + this.app = resolveApp(); + this.projects = readRecentProjects(readRecentGroups()); + } +} + +/** + * OpenIDEA 配置根目录 + * 优先用宿主提供的 appData(macOS: ~/Library/Application Support,Windows: %APPDATA%), + * 宿主不可用时按平台环境变量兜底 + * @returns 配置根目录路径 + */ +function getAppDataDir() { + try { + const appDataDir = window.ztools.getPath("appData"); + if (appDataDir) { + return appDataDir; + } + } catch (error) { + // 宿主不支持 getPath 时走环境变量兜底 + } + if (process.platform === "win32") { + return process.env.APPDATA || ""; + } + return path.join(process.env.HOME || "", "Library", "Application Support"); +} + +/** + * recent.json 绝对路径 + * @returns 文件路径 + */ +function getRecentFilePath() { + return path.join(getAppDataDir(), CONFIG_DIR_NAME, RECENT_FILE_NAME); +} + +/** + * recent-groups.json 绝对路径 + * @returns 文件路径 + */ +function getRecentGroupsFilePath() { + return path.join(getAppDataDir(), CONFIG_DIR_NAME, RECENT_GROUPS_FILE_NAME); +} + +/** + * 路径去重键:Windows 文件系统不区分大小写 + * @param projectPath 项目路径 + * @returns 去重键 + */ +function normalizePathKey(projectPath) { + return process.platform === "win32" ? projectPath.toLowerCase() : projectPath; +} + +/** + * 读取项目分组,返回 path → 组名 的映射 + * 归一规则与官方 normalize 一致:组名去空白、空名/重名丢弃、每个路径只归属第一个组; + * 不在 recent.json 里的路径自然查不到,无需额外处理 + * @returns 分组映射;文件不存在或格式异常时返回空 Map + */ +function readRecentGroups() { + const groupByPath = new Map(); + let groupList; + try { + groupList = JSON.parse(fs.readFileSync(getRecentGroupsFilePath(), "utf8")); + } catch (error) { + // 没有建过分组时文件不存在,属正常情况 + return groupByPath; + } + if (!Array.isArray(groupList)) { + return groupByPath; + } + + const seenNames = new Set(); + const seenPaths = new Set(); + for (const group of groupList) { + const groupName = typeof group?.name === "string" ? group.name.trim() : ""; + if (!groupName || seenNames.has(groupName)) { + continue; + } + seenNames.add(groupName); + + const groupPaths = Array.isArray(group.paths) ? group.paths : []; + for (const rawPath of groupPaths) { + const projectPath = typeof rawPath === "string" ? rawPath.trim() : ""; + if (!projectPath) { + continue; + } + const pathKey = normalizePathKey(projectPath); + if (seenPaths.has(pathKey)) { + continue; + } + seenPaths.add(pathKey); + groupByPath.set(pathKey, groupName); + } + } + return groupByPath; +} + +/** + * 读取最近项目列表 + * @param groupByPath 分组映射(path → 组名) + * @returns 项目数组;文件不存在或格式异常时返回空数组 + */ +function readRecentProjects(groupByPath) { + const recentFilePath = getRecentFilePath(); + let recentProjectList; + try { + recentProjectList = JSON.parse(fs.readFileSync(recentFilePath, "utf8")); + } catch (error) { + // 未安装/从未打开过项目时文件不存在,属正常情况 + return []; + } + if (!Array.isArray(recentProjectList)) { + return []; + } + + const projects = []; + const seenPaths = new Set(); + for (const item of recentProjectList) { + const projectPath = typeof item?.path === "string" ? item.path.trim() : ""; + if (!projectPath) { + continue; + } + // 同一路径只保留第一条(文件本身已去重,这里防止手改后出现重复项) + const pathKey = normalizePathKey(projectPath); + if (seenPaths.has(pathKey)) { + continue; + } + seenPaths.add(pathKey); + + // missing 字段是上次展示时写入的,可能过期:以磁盘实际状态重新判定 + const missing = isMissing(projectPath); + // branch 是上次打开时持久化的,官方展示前会从 .git/HEAD 刷新,这里保持一致 + const liveBranch = readLiveBranch(projectPath); + const storedBranch = typeof item.branch === "string" ? item.branch : ""; + + projects.push({ + path: projectPath, + name: String(item.name || path.basename(projectPath)).trim(), + branch: missing ? "" : liveBranch === undefined ? storedBranch : liveBranch, + openedAtMs: Number(item.openedAtMs) || 0, + missing: missing, + remote: isRemotePath(projectPath), + group: groupByPath.get(pathKey) || "" + }); + } + + // 最近打开的排在前面 + return projects.sort((prev, next) => next.openedAtMs - prev.openedAtMs); +} + +exports.initService = new InitService(); +exports.getRecentFilePath = getRecentFilePath; diff --git a/plugins/openidea-plugin/utils/launcher.js b/plugins/openidea-plugin/utils/launcher.js new file mode 100644 index 000000000..9e3420c04 --- /dev/null +++ b/plugins/openidea-plugin/utils/launcher.js @@ -0,0 +1,202 @@ +const fs = require("fs"); +const path = require("path"); +const { execFile, execFileSync } = require("child_process"); +const { isMissing, isRemotePath } = require("./project_path"); + +const APP_BUNDLE_NAME = "OpenIDEA.app"; + +/** + * 定位 OpenIDEA 安装位置 + * 每次调用都重新探测(成本只是几次 existsSync),应用刚安装/移动也能立即生效 + * @returns { appPath, cliPath, needsShell, icon } ;未安装时 appPath/cliPath 为空串 + */ +function resolveApp() { + if (process.platform === "win32") { + return resolveWindowsApp(); + } + return resolveMacApp(); +} + +/** + * macOS:安装目录即 .app 路径,CLI 是 bundle 内的 shell 脚本 + * @returns 应用信息 + */ +function resolveMacApp() { + const homeDir = process.env.HOME || ""; + const candidates = [ + path.join("/Applications", APP_BUNDLE_NAME), + path.join(homeDir, "Applications", APP_BUNDLE_NAME) + ]; + const appPath = candidates.find((candidate) => fs.existsSync(candidate)) || ""; + const cliPath = appPath + ? path.join(appPath, "Contents", "Resources", "bin", "openidea") + : ""; + return { + appPath: appPath, + cliPath: fs.existsSync(cliPath) ? cliPath : "", + needsShell: false, + icon: getFileIcon(appPath) + }; +} + +/** + * Windows:主程序是 openidea.exe,安装位置随安装方式不同; + * "安装 openidea 命令"会在 %LOCALAPPDATA%\OpenIDEA\bin 写一个 openidea.cmd 包装脚本 + * @returns 应用信息 + */ +function resolveWindowsApp() { + const localAppData = process.env.LOCALAPPDATA || ""; + const programFiles = process.env.ProgramFiles || ""; + const programFilesX86 = process.env["ProgramFiles(x86)"] || ""; + // 环境变量缺失时跳过对应候选:path.join("", ...) 会得到相对路径,可能误命中当前目录 + const installRoots = [localAppData, programFiles, programFilesX86].filter(Boolean); + const candidates = [ + ...installRoots.map((root) => path.join(root, "OpenIDEA", "openidea.exe")), + ...(localAppData ? [path.join(localAppData, "Programs", "OpenIDEA", "openidea.exe")] : []), + ...(localAppData ? [path.join(localAppData, "OpenIDEA", "bin", "openidea.cmd")] : []) + ]; + const installed = candidates.find((candidate) => fs.existsSync(candidate)); + if (installed) { + return buildWindowsApp(installed); + } + const onPath = findExecutableOnPath("openidea"); + return onPath ? buildWindowsApp(onPath) : { appPath: "", cliPath: "", needsShell: false, icon: "" }; +} + +/** + * 把找到的可执行文件/包装脚本归一为启动信息 + * @param commandPath exe 或 openidea.cmd 路径 + * @returns 应用信息 + */ +function buildWindowsApp(commandPath) { + // 包装脚本里带着真实 exe 路径:直接执行 exe 比经过 cmd.exe 更稳,也避免引号转义问题 + const isWrapper = /\.cmd$/i.test(commandPath); + const exePath = isWrapper ? readWrapperExecutable(commandPath) : commandPath; + const launchPath = exePath || commandPath; + return { + appPath: launchPath, + cliPath: launchPath, + // 解析不出真实 exe 时只能交给 cmd.exe 执行 .cmd + needsShell: !exePath, + icon: getFileIcon(exePath || commandPath) + }; +} + +/** + * 从 openidea.cmd 包装脚本中取真实 exe 路径 + * 脚本由 OpenIDEA 生成,形如 "" --cli %* + * @param wrapperPath 包装脚本路径 + * @returns exe 路径;解析失败返回空串 + */ +function readWrapperExecutable(wrapperPath) { + try { + const matched = /^"([^"]+)"\s+--cli/m.exec(fs.readFileSync(wrapperPath, "utf8")); + // 生成脚本时 % 被转义成 %%,这里还原 + return matched ? matched[1].replace(/%%/g, "%") : ""; + } catch (error) { + return ""; + } +} + +/** + * 在 PATH 中查找命令(Windows 的 where 会按 PATHEXT 命中 openidea.cmd) + * @param executableName 命令名 + * @returns 绝对路径;找不到时返回空串 + */ +function findExecutableOnPath(executableName) { + try { + const output = execFileSync("where", [executableName], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"] + }); + return String(output).split(/\r?\n/)[0].trim(); + } catch (error) { + return ""; + } +} + +/** + * 取应用图标(宿主不支持时返回空串) + * @param filePath 应用路径(macOS 传 .app,Windows 传 exe) + * @returns 图标路径 + */ +function getFileIcon(filePath) { + if (!filePath) { + return ""; + } + try { + return window.ztools.getFileIcon(filePath) || ""; + } catch (error) { + return ""; + } +} + +/** + * 在 OpenIDEA 中打开项目 + * @param projectPath 项目绝对路径 + */ +function launchProject(projectPath) { + if (typeof projectPath !== "string" || !projectPath.trim()) { + showNotification("项目路径无效"); + return; + } + const app = resolveApp(); + if (!app.appPath) { + showNotification("未找到 OpenIDEA,请先安装或手动指定路径"); + return; + } + // CLI 要求路径真实存在,缺失/远程项目直接调用只会得到一句英文报错,这里提前给出可读提示 + if (isRemotePath(projectPath)) { + showNotification("远程项目请从 OpenIDEA 欢迎页打开:" + projectPath); + return; + } + if (isMissing(projectPath)) { + showNotification("项目目录不存在:" + projectPath); + return; + } + + const onLaunched = (error) => { + if (!error) { + return; + } + console.error("launch project failed:", error.message); + showNotification("OpenIDEA 启动失败:" + String(error.message).split("\n")[0]); + }; + + if (process.platform === "darwin") { + // 优先用应用自带 CLI:会复用已运行实例,并按项目窗口打开 + if (app.cliPath) { + execFile(app.cliPath, [projectPath], onLaunched); + return; + } + // 兜底:CLI 缺失时交给 LaunchServices + execFile("/usr/bin/open", ["-a", app.appPath, projectPath], onLaunched); + return; + } + + if (app.needsShell) { + // .cmd 无法被 execFile 直接执行,必须经 cmd.exe;包装脚本内部已补 --cli + execFile( + process.env.ComSpec || "cmd.exe", + // /s 会剥掉首尾引号,因此整条命令要再包一层引号 + ["/d", "/s", "/c", '""' + app.cliPath + '" "' + projectPath + '""'], + onLaunched + ); + return; + } + // --cli 必须是第一个参数(CLI 用它识别命令行模式) + execFile(app.cliPath, ["--cli", projectPath], onLaunched); +} + +/** + * 系统通知(宿主不支持时忽略) + * @param message 通知内容 + */ +function showNotification(message) { + if (window.ztools && typeof window.ztools.showNotification === "function") { + window.ztools.showNotification(message); + } +} + +exports.resolveApp = resolveApp; +exports.launchProject = launchProject; diff --git a/plugins/openidea-plugin/utils/project_path.js b/plugins/openidea-plugin/utils/project_path.js new file mode 100644 index 000000000..175d16296 --- /dev/null +++ b/plugins/openidea-plugin/utils/project_path.js @@ -0,0 +1,100 @@ +const fs = require("fs"); +const path = require("path"); + +/** + * 远程项目路径(ssh://、wsl://、devcontainer:// 等) + * 这类路径在本机不存在属正常情况,不能按"目录缺失"处理 + * @param projectPath 项目路径 + * @returns 是否远程路径 + */ +function isRemotePath(projectPath) { + return String(projectPath || "").includes("://"); +} + +/** + * 判断项目目录是否真的缺失(与 OpenIDEA 欢迎页口径一致) + * 远程路径、WSL 共享目录、相对路径都不算缺失: + * WSL 发行版停止时目录不可见,但项目仍然有效 + * @param projectPath 项目路径 + * @returns 是否缺失 + */ +function isMissing(projectPath) { + const text = String(projectPath || ""); + if (!text || isRemotePath(text)) { + return false; + } + const uncPath = text.replace(/\//g, "\\").toLowerCase(); + if (uncPath.startsWith("\\\\wsl$") || uncPath.startsWith("\\\\wsl.localhost")) { + return false; + } + if (!path.isAbsolute(text)) { + return false; + } + return !fs.existsSync(text); +} + +/** + * 定位项目的 git 目录:普通仓库是 .git 目录,worktree 是 .git 文件里的 gitdir + * @param projectPath 项目路径 + * @returns git 目录;不是仓库时返回空串 + */ +function resolveGitDir(projectPath) { + const dotGit = path.join(projectPath, ".git"); + let stat; + try { + stat = fs.statSync(dotGit); + } catch (error) { + return ""; + } + if (stat.isDirectory()) { + return dotGit; + } + if (!stat.isFile()) { + return ""; + } + try { + const gitdirLine = fs + .readFileSync(dotGit, "utf8") + .split(/\r?\n/) + .find((line) => line.startsWith("gitdir:")); + const raw = gitdirLine ? gitdirLine.slice("gitdir:".length).trim() : ""; + if (!raw) { + return ""; + } + return path.isAbsolute(raw) ? raw : path.join(projectPath, raw); + } catch (error) { + return ""; + } +} + +/** + * 从 .git/HEAD 读取当前分支 + * 与 OpenIDEA 一致:refs/heads/* 取分支名,detached HEAD 取 7 位短提交 + * @param projectPath 项目路径 + * @returns 分支名;空串表示无分支;undefined 表示读取失败(保留存储值) + */ +function readLiveBranch(projectPath) { + const gitDir = resolveGitDir(projectPath); + if (!gitDir) { + return undefined; + } + let head; + try { + head = fs.readFileSync(path.join(gitDir, "HEAD"), "utf8").trim(); + } catch (error) { + return undefined; + } + if (!head) { + return ""; + } + if (head.startsWith("ref:")) { + const reference = head.slice("ref:".length).trim(); + const branchPrefix = "refs/heads/"; + return reference.startsWith(branchPrefix) ? reference.slice(branchPrefix.length) : ""; + } + return head.slice(0, 7); +} + +exports.isRemotePath = isRemotePath; +exports.isMissing = isMissing; +exports.readLiveBranch = readLiveBranch;