diff --git a/CHANGELOG.md b/CHANGELOG.md index f17ce0d..324f753 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog -## 0.1.0 +## 0.1.3 + +### Added +- Repository detection via `git rev-parse --is-inside-work-tree`; the panel now renders a dedicated "Create Git Repository" view when the project is not yet a Git repository. +- One-click repository initialization (`git init`) directly from the panel. +- VS Code-style staging: a per-file `+` button in the Changes list, plus a "Stage all" action. +- Unstaging via a per-file `-` button, including support for repositories with no commits yet. +- Commit workflow with a persistent message buffer, empty-message validation, and immediate status refresh after commit. +- Manual refresh button to force `git status` without waiting for the throttle interval. +- Files with dual status (e.g. `AM`) are now shown in both "Staged Changes" and "Changes", matching `git status` behavior. +### Planned +- Branch display and switching. +- File status coloring (Modified / Added / Deleted / Untracked). +- Discard changes action for unstaged files. +- Push / Pull controls. +- Diff preview for tracked files. +- Asynchronous `git status` execution to keep the editor responsive on large repositories. + +### Fixed +- Engine crash caused by calling `subprocess` synchronously from `on_enable`; Git detection is now performed lazily during the first render. +- `exit status 128` when `git status` was executed outside a repository or in the wrong working directory. +- Duplicate ImGui item IDs (`duplicate visible item ID`) caused by repeated `+` / `-` button labels inside loops. +- `Missing EndGroup()` errors when rendering was interrupted by an exception; `end_group()` is now guaranteed via `try/finally`. +- Commit button being a no-op because `text_input` reset its value to a placeholder every frame. +- "Stage all" button not responding due to overlapping with the collapsing header's hit area. + +### Changed +- Working directory is now always passed explicitly via `cwd=` to every Git subprocess. +- `files_status_list` replaced with three independent collections (`staged_files`, `unstaged_files`, `untracked_files`), allowing a single file to appear in multiple states simultaneously. +- Status parsing now uses `git status --porcelain` and updates the lists atomically, preserving the last known state on transient failures. +- `git status` refresh is throttled to once per second to avoid spawning a subprocess every frame. + +## 0.1.2 - Refactor example plugin name. diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 590ce44..97a77c5 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -1,5 +1,37 @@ # 更新日志 -## 0.1.1 +## 0.1.3 + +### 新增 +- 使用 `git rev-parse --is-inside-work-tree` 检测仓库;项目尚未初始化 Git 时,面板会显示独立的「创建 Git 仓库」界面。 +- 可在面板中一键初始化仓库(`git init`)。 +- 仿 VS Code 的暂存操作:Changes 列表每个文件右侧提供 `+` 按钮,并提供「Stage all」整体暂存。 +- 支持逐个文件取消暂存(`-` 按钮),兼容尚无任何提交的仓库。 +- 提交流程:持久化提交消息缓冲区、空消息校验,以及提交后立即刷新状态。 +- 手动刷新按钮,可绕过节流间隔强制执行 `git status`。 +- 双状态文件(如 `AM`)现在会同时出现在「Staged Changes」与「Changes」中,与 `git status` 的行为一致。 +### 计划 +- 分支显示与切换。 +- 文件状态着色(Modified / Added / Deleted / Untracked)。 +- 未暂存文件的「放弃更改」(Discard changes)操作。 +- Push / Pull 控制。 +- 已跟踪文件的 Diff 预览。 +- 异步执行 `git status`,在大仓库中保持编辑器响应。 + +### 修复 +- 在 `on_enable` 中同步调用 `subprocess` 导致引擎崩溃;Git 探测改为首次渲染时惰性执行。 +- 在仓库外或错误工作目录中执行 `git status` 时返回 `exit status 128`。 +- 循环内 `+` / `-` 按钮标签重复导致的 ImGui ID 冲突(`duplicate visible item ID`)。 +- 渲染中途抛异常导致 `Missing EndGroup()`;现通过 `try/finally` 保证 `end_group()` 一定被调用。 +- `text_input` 每帧把值重置为占位文本,导致提交按钮无效。 +- 「Stage all」按钮与折叠标题点击区域重叠导致无响应。 + +### 变更 +- 所有 Git 子进程调用现在都通过 `cwd=` 显式指定工作目录。 +- 以 `staged_files`、`unstaged_files`、`untracked_files` 三个独立集合取代 `files_status_list`,允许同一文件同时处于多个状态。 +- 状态解析改用 `git status --porcelain`,并以原子方式更新列表;临时失败时保留上一次的已知状态。 +- `git status` 刷新节流为每秒最多一次,避免每帧启动子进程。 + +## 0.1.2 - 重建插件引擎实例名称。 diff --git a/package/editor/translations.json b/package/editor/translations.json index fe4b8e5..6fb97a9 100644 --- a/package/editor/translations.json +++ b/package/editor/translations.json @@ -2,18 +2,12 @@ "$schema": "infernux.editor_translations", "locales": { "en": { - "wokrlie.git_integration.menu_diagnostics": "Diagnostics", - "wokrlie.git_integration.menu_live": "Live", - "wokrlie.git_integration.menu_root": "Example Plugin", - "wokrlie.git_integration.menu_tools": "Tools", - "wokrlie.git_integration.panel_title": "Example Plugin" + "wokrlie.git_integration.menu_root": "Git Integration", + "wokrlie.git_integration.panel_title": "Git Integration" }, "zh": { - "wokrlie.git_integration.menu_diagnostics": "诊断", - "wokrlie.git_integration.menu_live": "实时", - "wokrlie.git_integration.menu_root": "示例插件", - "wokrlie.git_integration.menu_tools": "工具", - "wokrlie.git_integration.panel_title": "示例插件" + "wokrlie.git_integration.menu_root": "Git集成", + "wokrlie.git_integration.panel_title": "Git集成" } } } diff --git a/package/editor/wokrlie/git_integration/panel.py b/package/editor/wokrlie/git_integration/panel.py index f8f3e88..8a08c67 100644 --- a/package/editor/wokrlie/git_integration/panel.py +++ b/package/editor/wokrlie/git_integration/panel.py @@ -3,29 +3,403 @@ from infernux.engine.interaction import PanelInteractionDescriptor from infernux.engine.ui.editor_panel import EditorPanel from infernux.engine.ui.panel_registry import editor_panel - +from infernux import Debug +import subprocess, time, os @editor_panel( "Git integration", type_id="wokrlie.git_integration", title_key="wokrlie.git_panel", - menu_path="Extensions/Git Integration/Tools/Diagnostics/Live", + menu_path="Extensions/Git Integration", menu_path_keys=( "menu.extensions", "wokrlie.git_integration.menu_root", - "wokrlie.git_integration.menu_tools", - "wokrlie.git_integration.menu_diagnostics", - "wokrlie.git_integration.menu_live", ), interaction=PanelInteractionDescriptor(), ) + + class GitIntegrationPanel(EditorPanel): def __init__(self) -> None: super().__init__("Git Integration", "wokrlie.git_integration.panel") - def _intial_size(self) -> tuple[float, float]: - return 420.0, 240.0 + self.have_git: bool = False + self.is_repo_initialized: bool = False + self.files_status_list: dict[str, str] = {} + + self._commit_message: str = "" + self._last_refresh: float = 0.0 + self._refresh_interval: float = 1.0 + self._git_checked: bool = False + + # 项目根目录,优先从引擎获取,否则回退到当前工作目录 + self.repo_path: str = os.getcwd() + + # ------------------------------------------------------------------ # + # 生命周期(保持惰性初始化,避免 on_enable 崩溃) + # ------------------------------------------------------------------ # + def on_enable(self) -> None: + self._git_checked = False + self.have_git = False + self.is_repo_initialized = False def on_render_content(self, ctx) -> None: - ctx.label("Git Integration") - ctx.text_wrapped("This panel was registered by the plugin preload lifecycle.") + if not self._git_checked: + self._check_git_availability() + self._git_checked = True + + if not self.have_git: + ctx.label("Git is not usable in current environment.") + return + + # 节流刷新仓库状态 + now = time.time() + if now - self._last_refresh >= self._refresh_interval: + self.refresh_git_status() + self._last_refresh = now + + # ==================== 分支渲染 ==================== + if not self.is_repo_initialized: + self._render_no_repo_ui(ctx) # 未初始化仓库:只显示创建按钮 + return + + self._render_git_ui(ctx) # 已初始化仓库:正常 Git 操作界面 + # =================================================== + + def _render_git_ui(self, ctx) -> None: + ctx.label("Source Control") + ctx.same_line() + ctx.button("⟳##refresh_git", self._manual_refresh, 28.0, 20.0) + + ctx.begin_group("Changes") + try: + self._render_staged_section(ctx) + self._render_changes_section(ctx) + + # -------- 提交消息 -------- + ctx.label("Commit message:") + self._try_set_next_item_width(ctx, 380.0) + self._commit_message = ctx.text_input( + label="##commit_msg", + value=self._commit_message, # ← 持久状态,不再用提示字面量 + ) + + # -------- 提交按钮 -------- + commit_msg = self._commit_message + ctx.button( + "Check in staged changes", + lambda: self.check_in_staged_changes(commit_msg), + 380.0, # ← 加宽,避免文字被截断 + 30.0, + ) + finally: + ctx.end_group() + + + def _try_set_next_item_width(self, ctx, width: float) -> None: + """ImGui 的 SetNextItemWidth 若已绑定则使用,否则降级为默认宽度。""" + try: + ctx.set_next_item_width(width) + except (AttributeError, TypeError): + pass + + + def _render_staged_section(self, ctx) -> None: + expanded = ctx.collapsing_header(f"Staged Changes ({len(self.staged_files)})") + if not expanded: + return + + if not self.staged_files: + ctx.label(" (none)") + return + + for path, status in sorted(self.staged_files.items()): + ctx.label(f" {status} {path}") + ctx.same_line() + ctx.button( + f"-##unstage_{path}", + lambda p=path: self.unstage_file(p), + 20.0, + 18.0, + ) + + + def _render_changes_section(self, ctx) -> None: + total = len(self.unstaged_files) + len(self.untracked_files) + expanded = ctx.collapsing_header(f"Changes ({total})") + + # Stage all 放到 header 下一行,避免 same_line 遮挡点击区域 + if total > 0: + ctx.button( + "Stage all##stage_all", + self.stage_all, + 120.0, + 22.0, + ) + + if not expanded: + return + + if total == 0: + ctx.label(" (none)") + return + + for path, status in sorted(self.unstaged_files.items()): + ctx.label(f" {status} {path}") + ctx.same_line() + ctx.button( + f"+##stage_{path}", + lambda p=path: self.stage_file(p), + 20.0, + 18.0, + ) + + for path in sorted(self.untracked_files): + ctx.label(f" ? {path}") + ctx.same_line() + ctx.button( + f"+##stage_{path}", + lambda p=path: self.stage_file(p), + 20.0, + 18.0, + ) + + # ------------------------------------------------------------------ # + # Git 可用性检测(与仓库检测分离) + # ------------------------------------------------------------------ # + def _check_git_availability(self) -> None: + try: + result = subprocess.run( + ["git", "--version"], + capture_output=True, + text=True, + timeout=5, + ) + self.have_git = result.returncode == 0 + except (FileNotFoundError, subprocess.TimeoutExpired): + self.have_git = False + + if not self.have_git: + Debug.error("Git is not usable in current environment.") + + # ------------------------------------------------------------------ # + # 刷新:先检测仓库是否存在,再拉取文件状态 + # ------------------------------------------------------------------ # + def refresh_git_status(self) -> None: + """Run `git status --porcelain` and rebuild the three file lists. + + - ``AM path`` 这类文件会**同时**出现在 staged 和 unstaged 两个列表中, + 与 `git status` / VSCode 的显示一致。 + """ + staged: dict[str, str] = {} + unstaged: dict[str, str] = {} + untracked: list[str] = [] + + if not self._is_inside_work_tree(): + self.is_repo_initialized = False + self.staged_files = {} + self.unstaged_files = {} + self.untracked_files = [] + return + + self.is_repo_initialized = True + + try: + result = subprocess.run( + ["git", "status", "--porcelain"], + capture_output=True, + text=True, + check=True, + cwd=self.repo_path, + timeout=5, + ) + except (FileNotFoundError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc: + Debug.error(f"`git status` failed: {exc}") + return + + for raw in result.stdout.splitlines(): + if len(raw) < 4: + continue + + index_status = raw[0] + worktree_status = raw[1] + path = raw[3:].strip() + + if " -> " in path: + path = path.split(" -> ", 1)[1] + + if index_status == "?" and worktree_status == "?": + untracked.append(path) + continue + + if index_status == "!" and worktree_status == "!": + continue + + # 关键:X 和 Y 独立判断,不再互斥 + if index_status not in (" ", "?"): + staged[path] = index_status + if worktree_status not in (" ", "?"): + unstaged[path] = worktree_status + + self.staged_files = staged + self.unstaged_files = unstaged + self.untracked_files = untracked + + def _is_inside_work_tree(self) -> bool: + """使用 `git rev-parse --is-inside-work-tree` 判断是否在 Git 工作树中。""" + try: + result = subprocess.run( + ["git", "rev-parse", "--is-inside-work-tree"], + capture_output=True, + text=True, + cwd=self.repo_path, + timeout=5, + ) + return result.returncode == 0 and result.stdout.strip() == "true" + except (FileNotFoundError, subprocess.TimeoutExpired): + return False + + # ------------------------------------------------------------------ # + # 初始化仓库 + # ------------------------------------------------------------------ # + def init_git_repo(self) -> None: + """在当前项目目录初始化一个新的 Git 仓库。""" + try: + result = subprocess.run( + ["git", "init"], + capture_output=True, + text=True, + cwd=self.repo_path, + timeout=10, + ) + except FileNotFoundError: + Debug.error("Git is not installed.") + return + except subprocess.TimeoutExpired: + Debug.error("`git init` timed out.") + return + + if result.returncode == 0: + # 初始化成功后立即刷新状态,面板会切换到"已初始化"分支 + self.refresh_git_status() + self._last_refresh = time.time() + else: + Debug.error(f"`git init` failed: {result.stderr.strip()}") + + # ------------------------------------------------------------------ # + # 提交(仅在有仓库时可用) + # ------------------------------------------------------------------ # + def check_in_staged_changes(self, msg: str) -> None: + if not msg or not msg.strip(): + Debug.error("Commit message is empty.") + return + + if not self.is_repo_initialized: + Debug.error("No Git repository. Please create one first.") + return + + try: + result = subprocess.run( + ["git", "commit", "-m", msg], + capture_output=True, + text=True, + cwd=self.repo_path, + timeout=10, + ) + except (FileNotFoundError, subprocess.TimeoutExpired) as exc: + Debug.error(f"`git commit` failed: {exc}") + return + + if result.returncode == 0: + self._commit_message = "" # 成功后清空,符合 VSCode 习惯 + self._refresh_after_mutation() + else: + # 常见失败:没有 staged changes / user.name 未配置 / 钩子拒绝 + Debug.error(f"`git commit` failed: {result.stderr.strip()}") + + def stage_file(self, path: str) -> None: + """暂存单个文件(包括新增、修改、删除)。 + + 使用 ``--`` 分隔符避免路径被误当作选项;对已删除文件,`git add ` + 同样会记录删除操作(Git 2.x 起)。 + """ + if not self.is_repo_initialized: + Debug.error("No Git repository. Please create one first.") + return + + try: + result = subprocess.run( + ["git", "add", "--", path], + capture_output=True, + text=True, + cwd=self.repo_path, + timeout=10, + ) + except (FileNotFoundError, subprocess.TimeoutExpired) as exc: + Debug.error(f"`git add` failed: {exc}") + return + + if result.returncode == 0: + self._refresh_after_mutation() + else: + Debug.error(f"`git add {path}` failed: {result.stderr.strip()}") + + + def stage_all(self) -> None: + """暂存所有变更(等价于 `git add -A`,包含修改、新增和删除)。""" + if not self.is_repo_initialized: + Debug.error("No Git repository. Please create one first.") + return + + try: + result = subprocess.run( + ["git", "add", "-A"], + capture_output=True, + text=True, + cwd=self.repo_path, + timeout=10, + ) + except (FileNotFoundError, subprocess.TimeoutExpired) as exc: + Debug.error(f"`git add -A` failed: {exc}") + return + + if result.returncode == 0: + self._refresh_after_mutation() + else: + Debug.error(f"`git add -A` failed: {result.stderr.strip()}") + + + def unstage_file(self, path: str) -> None: + if not self.is_repo_initialized: + return + + # 尝试1: 标准情况 (有 HEAD 时可用) + # 使用 `git reset HEAD -- ` 是 VS Code 的主要方式 + result = subprocess.run( + ["git", "reset", "HEAD", "--", path], + capture_output=True, text=True, cwd=self.repo_path, timeout=10, + ) + if result.returncode == 0: + self._refresh_after_mutation() + return + + # 尝试2: 无提交历史 (No commits yet) 的回退 + # 不指定 HEAD,直接清空该路径的暂存条目 + fallback = subprocess.run( + ["git", "reset", "--", path], + capture_output=True, text=True, cwd=self.repo_path, timeout=10, + ) + if fallback.returncode == 0: + self._refresh_after_mutation() + else: + Debug.error(f"unstage failed: {fallback.stderr.strip()}") + + + def _refresh_after_mutation(self) -> None: + """任何 stage/unstage/commit 之后调用,立即刷新状态并重置节流计时。""" + self.refresh_git_status() + self._last_refresh = time.time() + + def _manual_refresh(self) -> None: + self.refresh_git_status() + self._last_refresh = time.monotonic() \ No newline at end of file diff --git a/package/editor/wokrlie/git_integration/preload.py b/package/editor/wokrlie/git_integration/preload.py index 2dec195..afc3990 100644 --- a/package/editor/wokrlie/git_integration/preload.py +++ b/package/editor/wokrlie/git_integration/preload.py @@ -10,7 +10,7 @@ def preload(self, context: PreloadContext) -> None: # Imports performed here are attributed to this lifecycle transaction. # The Editor removes contributed panels, commands, and shortcuts before # reloading this file, disabling the plugin, or closing the project. - import_module("wokrlie.git_integration.panel") + import_module(".panel", package=__package__) def unload(self) -> None: pass diff --git a/package/inx_package.json b/package/inx_package.json index 5166b0b..a97e614 100644 --- a/package/inx_package.json +++ b/package/inx_package.json @@ -2,7 +2,7 @@ "$schema": "infernux.inxpackage.source", "reference": "wokrlie/git_integration", "name": "Git Integration", - "version": "0.1.1", + "version": "0.1.3", "engine": ">=0.4.1,<0.5", "intro": "A simple git integration for infernux engine" } diff --git a/package/plugin_pages/usage.md b/package/plugin_pages/usage.md index c26c794..351c1ca 100644 --- a/package/plugin_pages/usage.md +++ b/package/plugin_pages/usage.md @@ -1,3 +1,39 @@ -# Git Integration Intro +# Git Panel -This repository will integrate a simple git panel for infernux engine to simplify git operations. \ No newline at end of file +The Git panel lets you stage, unstage, and commit changes from inside the Infernux editor, without switching to a terminal. +## Opening the panel +You can find it in the menu bar: `Extensions/ GitIntegration` +## Before you start + +The panel works on the project folder currently open in the editor. If that folder is not a Git repository yet, the panel shows a Create Git Repository view instead of the normal layout. Click Create Git Repository to run git init on the project folder; the panel then switches to the normal view. +The panel layout + +The normal view has three parts, from top to bottom: + + - Staged Changes — files that will be included in the next commit. + - Changes — files that have been modified or deleted but are not staged yet. + - Commit area — a message box, a Commit button, and a Refresh button. + +A file can appear in both lists at once. For example, a file that was staged and then modified again shows up under Staged Changes and under Changes, so you can tell it has both staged and unstaged content. + +## Staging and unstaging + + - To stage a single file, click the + button on its row in Changes. + - To stage everything in Changes at once, click Stage all. + - To unstage a file, click the − button on its row in Staged Changes. This also works in a repository that has no commits yet. + +## Committing + + - Type a message into the message box. The text stays there while you keep working in the panel. + + - Click Commit. The commit is created and the file lists refresh right away. + + - If the message box is empty, the commit button does nothing — enter a message first. + +## Refreshing the file lists + +The panel updates the file lists automatically. If you want to see the current state immediately — for example after running Git commands in a terminal — click Refresh. + +## Upcoming features + +Branch display and switching, file status coloring, discard-changes for unstaged files, Push/Pull controls, and diff preview are planned for future versions. \ No newline at end of file diff --git a/package/plugin_pages/usage.zh-CN.md b/package/plugin_pages/usage.zh-CN.md index a2f2fb6..b1978ce 100644 --- a/package/plugin_pages/usage.zh-CN.md +++ b/package/plugin_pages/usage.zh-CN.md @@ -1,6 +1,41 @@ -# Git集成介绍 +# Git 面板 -这个仓库会给Infernux引擎添加一个git panel的面板,便于操作 +Git 面板让你直接在 Infernux 编辑器里完成暂存、取消暂存和提交,不用切到终端。 +## 打开面板 +你可以再菜单栏的`插件/Git集成` +# 开始之前 -## 界限 -- 本仓库的所有操作都不涉及runtime, 单纯修改editor。 \ No newline at end of file +面板作用于当前在编辑器中打开的项目文件夹。如果这个文件夹还不是 Git 仓库,面板不会显示正常界面,而是显示 Create Git Repository 视图。点击 Create Git Repository 会对项目文件夹执行 git init,之后面板自动切换到正常界面。 +## 面板结构 + +正常界面从上到下分三部分: + + - Staged Changes —— 下次提交会包含的文件。 + + - Changes —— 已修改或删除、但还没暂存的文件。 + + - 提交区 —— 消息输入框、Commit 按钮和 Refresh 按钮。 + +一个文件可以同时出现在两个列表里。例如某个文件暂存之后又被修改,它会同时显示在 Staged Changes 和 Changes 中,这样你能看出它既有已暂存的内容,也有未暂存的改动。 +暂存与取消暂存 + + - 暂存单个文件:点击 Changes 中该文件右侧的 + 按钮。 + + - 一次性暂存 Changes 里的全部文件:点击 Stage all。 + + - 取消暂存:点击 Staged Changes 中该文件右侧的 − 按钮。仓库还没有任何提交时,这个操作同样可用。 + +## 提交 + + - 在消息输入框中填写提交信息。你在面板里继续操作时,输入的内容不会丢失。 + + - 点击 Commit,提交会被创建,文件列表随即刷新。 + + - 如果消息输入框为空,点击 Commit 不会有任何效果,需要先填写提交信息。 + +## 刷新文件列表 + +面板会自动更新文件列表。如果你想立刻看到当前状态——比如刚在终端里执行过 Git 命令——点击 Refresh。 +## 后续计划 + +后续版本将支持分支显示与切换、文件状态着色、未暂存文件的丢弃改动、Push / Pull 控制以及 diff 预览。 \ No newline at end of file