diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ae54f9..8cfa629 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,36 @@ All notable changes to the Git Integration plugin are documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## 0.2.1 + +### Added + +- **Branch management from the panel.** A **Branches** section in the panel shows the branch the project is on — with its upstream and how far it has drifted from it (`↑2 ↓1`) — and lists the local branches together with the remote ones Git already knows about. The branches arrive together with the file lists in one background pass, so the list is always the one the repository actually has. Typing in the filter box narrows the list down; the filter only changes what is shown and runs no command. +- **Switching branches.** Clicking a branch selects it — the selected branch is marked with an arrow — and the actions below the list apply to it. **Checkout** switches to it with `git checkout`. The switch runs on a worker thread, so the panel stays responsive even in a large repository. +- **Creating a branch from the panel.** A row at the bottom of the section takes a new branch name and creates it from the current `HEAD`, then switches to it. The name is checked with `git check-ref-format --branch` before it is used, so Git itself decides what a valid branch name is, and a name starting with `-` is refused before it can reach a command line. +- **Deleting a branch.** **Delete** removes the selected branch and lets git refuse a branch whose commits were never merged. **Force delete** removes it anyway, and git's reflog still keeps those commits. +- **Renaming a branch.** **Rename** opens a field for the new name. The name is checked with `git check-ref-format --branch` first, so a name git would refuse never reaches the command. +- **The commit log of a branch.** The **Branch log** section lists the last 50 commits of the selected branch, newest first, each with its short hash and its subject. The log is fetched in the background, so a branch with a long history does not stall the frame. +- **A failure dialog that points at the Console.** A failed branch operation opens a modal with one sentence about what went wrong, a note that the full message was written to the Console, and three buttons: *Open Console*, *Copy details*, and *Close*. The common Git failures each get their own sentence — local changes that the switch would overwrite, a branch that no longer exists, an invalid name, a name that is already taken, and a branch that another worktree holds. + +### Changed + +- **Every git command now runs on a worker thread.** Status collection, staging, unstaging, committing, `git init`, the branch listing, the branch log, and the checkout itself all happen off the render thread, which only draws the last snapshot it received. A large repository no longer stalls the Editor, and a checkout that takes a while no longer freezes the frame. +- **The status comes from `git status --porcelain=v2 -z --branch`.** One call now returns the branch name, the upstream, the ahead/behind counters, and the file list, instead of the file list alone. The `-z` form keeps a path that is not plain ASCII literal, where the older format quoted it as an octal escape. +- **Git output is decoded as UTF-8 on purpose.** The panel no longer depends on the console code page of the machine it runs on, so Chinese commit messages and Chinese file names survive on a Windows that is not running in UTF-8. +- Every call to `git` now lives in the new `package/editor/wokrlie/git_integration/git.py` module, so the panel no longer talks to `subprocess` itself. That module never touches the Engine API, which is what makes it safe to call from a worker thread. +- **The panel runs no git command on the render thread at all.** Whether git is usable is answered by the exit code of the status command instead of a separate `git --version` probe, and a branch name is validated on the worker thread instead of while the frame is being drawn. + +### Fixed + +- **The panel reported Git failures as Python tracebacks instead of the real error.** Every failure path called `Debug.error(...)`, which is not an Engine API — the Engine provides `Debug.log_error`. The call raised `AttributeError` before the Git message could be logged, so the reason a commit, a stage, or `git init` failed never reached the Console. The errors are now written with `Debug.log_error(...)` and tagged with the plugin's source, so the Console can group and clear them. The entry quotes the command line, the exit code, and Git's own message, so the failure can be reproduced by hand. +- **Unstaging a file raised `TypeError: 'function' object is not subscriptable`.** The action passed a function where the command factory expects the argument list of a git command, and the factory reads the first argument to name the worker thread, so the file was never unstaged. `git reset HEAD -- ` unstages it on its own, and it also works in a repository that has no commit yet: git falls back to the empty tree and the file returns to being untracked. +- **Non-ASCII file names were shown as octal escapes.** The old parser read the v1 porcelain format, in which Git quotes a path that is not plain ASCII, so a file called `文档/说明.md` appeared as `"\346\226\207..."`. The panel now reads the `-z` format, where the path is written literally. + +### Requirements + +- **Git 2.13 or newer.** `git status --porcelain=v2` needs Git 2.11, and the `%(upstream:short)` field of `git for-each-ref` needs Git 2.13. Both are from 2016 and 2017; any current distribution is well past them. + ## 0.1.5 ### Added diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index b85cc06..f9653aa 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -2,6 +2,36 @@ Git 集成插件的所有重要变更都记录在本文件中。格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),版本号遵循[语义化版本](https://semver.org/lang/zh-CN/)。 +## 0.2.1 + +### 新增 + +- **在面板里管理分支。** 面板的**分支**分组显示项目当前所在的分支——连同它的上游和与上游的偏差(`↑2 ↓1`)——并列出本地分支和 Git 已知的远端分支。分支和文件列表在同一次后台任务里一起取回来,所以列表始终和仓库实际情况一致。在过滤框里输入内容可以缩小列表范围;过滤只是改变显示内容,不会执行任何命令。 +- **切换分支。** 点击某个分支会选中它——选中的分支前面有一个箭头标记——下方的操作都作用于它。**切换**用 `git checkout` 切过去。切换在工作线程上执行,即使在大仓库里面板也不会卡住。 +- **在面板里新建分支。** 分组底部有一行输入框,填入新分支名即可从当前 `HEAD` 创建并切换过去。分支名在使用前会先交给 `git check-ref-format --branch` 校验,由 Git 自己决定什么才是合法分支名;以 `-` 开头的名字在进入命令行之前就会被拒绝。 +- **删除分支。** **删除**会移除选中的分支,并让 git 拒绝删除还有未合并提交的分支。**强制删除**则照样删掉,那些提交仍留在 git 的 reflog 里。 +- **重命名分支。** **重命名**会展开一个输入框让你填新名字。新名字会先经过 `git check-ref-format --branch` 校验,git 不接受的名字根本不会进入命令。 +- **分支的提交日志。** **分支日志**分组按时间倒序列出所选分支最近 50 个提交,每条带短哈希和提交信息。日志在后台获取,历史再长的分支也不会卡住那一帧。 +- **指向 Console 的失败弹窗。** 分支操作失败时会弹出模态框,用一句话说明出了什么问题,并提示完整信息已写入 Console,同时提供「打开 Console」「复制详情」「关闭」三个按钮。常见的 Git 失败各有对应的说法——切换会覆盖本地修改、分支已不存在、名字不合法、同名分支已存在、分支被另一个 worktree 占用。 + +### 变更 + +- **所有 Git 命令都改到后台线程执行。** 状态采集、暂存、取消暂存、提交、`git init`、分支列举、分支日志以及切换本身都在渲染线程之外完成,渲染线程只画它收到的上一份快照。大仓库不再拖慢编辑器,切换耗时较久时也不会卡住那一帧。 +- **状态改用 `git status --porcelain=v2 -z --branch` 采集。** 一次调用就能同时拿到分支名、上游、领先/落后计数和文件列表,而不再只有文件列表。`-z` 形式让非 ASCII 路径保持字面量,旧格式则会把它写成八进制转义。 +- **Git 输出显式按 UTF-8 解码。** 面板不再依赖运行机器的代码页,中文提交信息和中文文件名在非 UTF-8 的 Windows 上也能正确显示。 +- 所有 `git` 调用都集中到了新增的 `package/editor/wokrlie/git_integration/git.py` 模块,面板不再直接调用 `subprocess`。该模块不触碰任何引擎 API,这正是它能在工作线程里安全运行的前提。 +- **面板在渲染线程上一个 Git 命令都不跑了。** git 到底能不能用,改由状态命令的退出码回答,不再单独探一次 `git --version`;分支名的校验也挪到了工作线程上,而不是在绘制这一帧时顺手做掉。 + +### 修复 + +- **面板把 Git 失败报成了 Python 堆栈,而不是真正的错误。** 所有失败分支都调用了 `Debug.error(...)`,但引擎没有这个 API——引擎提供的是 `Debug.log_error`。调用在错误信息写入前就抛了 `AttributeError`,所以提交、暂存、`git init` 失败的真实原因从来没进过 Console。现在改用 `Debug.log_error(...)` 写入,并带上插件来源标记,Console 里可以按来源分组和清除。条目里会写明完整命令行、退出码和 Git 自己的报错,可以照着手动复现。 +- **取消暂存文件时抛 `TypeError: 'function' object is not subscriptable`。** 那个操作把函数传给了本该接收命令参数列表的工厂,而工厂要读第一个参数来给工作线程命名,于是文件根本没被取消暂存。`git reset HEAD -- ` 一条命令就够:仓库还没有提交时 git 会退回空树,文件回到未跟踪状态。 +- **非 ASCII 文件名显示成了八进制转义。** 旧解析器读的是 v1 porcelain 格式,Git 在该格式里会给非纯 ASCII 路径加引号并转义,于是 `文档/说明.md` 显示为 `"\346\226\207..."`。现在改读 `-z` 格式,路径是字面量。 + +### 环境要求 + +- **需要 Git 2.13 或更新版本。** `git status --porcelain=v2` 需要 Git 2.11,`git for-each-ref` 的 `%(upstream:short)` 字段需要 Git 2.13。两者分别来自 2016 年和 2017 年,当前任何发行版都已远超。 + ## 0.1.5 ### 新增 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 423cec3..b0dd04e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,7 +50,9 @@ python package.py build dist/plugin.inxpkg && python package.py verify dist/plug ## Code conventions - The Editor half of the plugin lives in `package/editor/`, the player-facing half in `package/runtime/`. Runtime code must not import Editor modules; the validator enforces that boundary. +- Every `git` call lives in `package/editor/wokrlie/git_integration/git.py`. The panel must not run a git command itself — that module is the only place that knows how git is invoked, how its output is decoded, and how its output is parsed. - Every `git` call must pass `cwd=` explicitly so the panel always operates on the folder open in the Editor. +- Git commands run on a worker thread, never on the render thread. `GitCommand` in `git.py` starts one and the render thread only polls it for the result. A module in `git.py` must never touch the Engine API, because it also runs off the render thread. - Use `subprocess.run` with a timeout. The render thread must never block indefinitely. - Panel state that survives a render lives on the instance; it is never stored in a module-level global. diff --git a/README.md b/README.md index 97abb1f..9507053 100644 --- a/README.md +++ b/README.md @@ -18,16 +18,19 @@ A source control panel for the [Infernux Engine](https://github.com/ChenlizheMe/ - Vector icons for the stage, unstage, stage-all, and refresh controls, plus a status icon and a coloured status code on every file row. - Localized panel UI in English and Simplified Chinese. - The plugin's own licence and the notices for the bundled icon artwork ship with the plugin and are shown on the **License** page of the plugin information. +- Branch management from the panel: a **Branches** section shows the current branch with its upstream, lists the local and remote branches, and switches, creates, renames, and deletes them. The selected branch also shows its commit log. Failures are reported in the Console. ## Requirements | Requirement | Version | | --- | --- | | Infernux Engine | `>=0.4.1,<0.5` | -| Git | A recent version available on your `PATH` | +| Git | `>=2.13` available on your `PATH` | Git is a **runtime requirement**. The panel shells out to the `git` executable; when it is missing, the panel shows a short notice instead of the file lists. +Git 2.13 is the floor because the panel reads `git status --porcelain=v2` (needs 2.11) and the `%(upstream:short)` field of `git for-each-ref` (needs 2.13). Both are from 2016 and 2017, so any current distribution is well past them. + The icons are vector artwork that the Editor rasterizes at runtime. That relies on the Engine's LunaSVG-backed texture loader, which is not part of the documented plugin API — if a future Engine release drops it, the panel falls back to text-only controls and everything else keeps working. ## Installation diff --git a/README.zh-CN.md b/README.zh-CN.md index acf503b..55760bb 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -18,16 +18,19 @@ - 暂存、取消暂存、暂存全部和刷新按钮使用矢量图标;每个文件行还带有状态图标和带颜色的状态码。 - 面板界面支持英文与简体中文。 - 插件自身的许可证和内置图标素材的第三方声明随插件一起分发,可在插件信息的**许可证**页面查看。 +- 在面板里管理分支:**分支**分组显示当前分支和它的上游,列出本地与远端分支,可以切换、新建、重命名和删除它们;选中分支还能查看它的提交日志。失败信息会写进 Console。 ## 环境要求 | 依赖 | 版本 | | --- | --- | | Infernux 引擎 | `>=0.4.1,<0.5` | -| Git | `PATH` 中可用的较新版本 | +| Git | `PATH` 中可用的 `>=2.13` 版本 | Git 是**运行时依赖**。面板通过 `git` 可执行文件完成所有操作;Git 缺失时,面板会显示一条简短提示而不是文件列表。 +之所以要求 Git 2.13,是因为面板要读 `git status --porcelain=v2`(需要 2.11)以及 `git for-each-ref` 的 `%(upstream:short)` 字段(需要 2.13)。两者分别来自 2016 年和 2017 年,当前任何发行版都已远超。 + ## 安装 ### 从发布页安装 diff --git a/RELEASING.md b/RELEASING.md index ea55ac2..dc569ef 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -10,7 +10,7 @@ Releases are produced by GitHub Actions. No artifact is uploaded by hand. | Engine compatibility | `package/inx_package.json` → `engine` | | Release notes | `CHANGELOG.md` and `CHANGELOG.zh-CN.md` | -The release tag must match the manifest version exactly — `v0.1.5` for version `0.1.5`. `package.py release-manifest` fails on any mismatch, so a mistyped tag stops the release instead of publishing a mislabelled archive. +The release tag must match the manifest version exactly — `v0.2.1` for version `0.2.1`. `package.py release-manifest` fails on any mismatch, so a mistyped tag stops the release instead of publishing a mislabelled archive. ## Procedure @@ -19,8 +19,8 @@ The release tag must match the manifest version exactly — `v0.1.5` for version 3. Tag the merge commit and push the tag: ```bash - git tag v0.1.5 - git push origin v0.1.5 + git tag v0.2.1 + git push origin v0.2.1 ``` 4. The `release` job runs on the tag. It builds the archive, verifies it, checks that two independent builds are byte-identical, generates `infernux-plugin-release.json`, and publishes both files as GitHub Release assets. @@ -44,7 +44,7 @@ Because of this, a fix for a published version needs a **new** version number. N python package.py build dist/wokrlie.git_integration.inxpkg python package.py verify dist/wokrlie.git_integration.inxpkg python package.py release-manifest dist/wokrlie.git_integration.inxpkg \ - --tag v0.1.5 --output dist/infernux-plugin-release.json + --tag v0.2.1 --output dist/infernux-plugin-release.json ``` The build is deterministic: running it twice over the same source must produce byte-identical archives, which is what CI asserts before it publishes anything. diff --git a/ROADMAP.md b/ROADMAP.md index a52c6a1..3dd6bff 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,14 +4,13 @@ Planned work for the Git Integration plugin. Delivered changes are recorded in [ ## Next -- **Branch display and switching** — show the current branch, and let the user switch or create branches from the panel. - **Discard changes** — revert the unstaged modifications of a single file. - **Push / Pull controls** — fetch, pull, and push without leaving the Editor. - **Diff preview** — show the content diff of a tracked file. -- **Asynchronous `git status`** — move status collection off the render thread so large repositories do not stall the Editor. +- **Migrate the Git worker to an editor preload** — the panel starts daemon threads today, and the Engine cannot stop those deterministically. The plugin authoring guide recommends that long-lived background work lives in `editor/` and is owned by an `InxPreload`, with a registered cleanup that stops the worker and joins it within a bound; it shows that shape with a Flask service bound to loopback on an operating-system allocated port, with the development reloader disabled. The HTTP service itself is only worth building if something outside the Editor has to drive Git — the panel should keep talking to its worker in process. ## Notes -Every item above has to keep the render thread responsive. The panel currently shells out to `git` synchronously during rendering, with a one-second throttle between refreshes. Asynchronous status collection is listed last because it is the change that makes the rest cheap to add: once status collection no longer blocks the frame, per-file operations can follow the same pattern. +Every item above has to keep the render thread responsive. Since 0.2.1 the panel runs every git command on a worker thread and draws the last snapshot it received, so the per-file operations follow the same pattern instead of blocking the frame. The status refresh is still throttled to one call per second, because a snapshot that is one second old is already too old to act on. Adding an item to this file is welcome — open a pull request that describes the user problem it solves, not just the API it would use. diff --git a/package/editor/translations.json b/package/editor/translations.json index 580099d..1d9f6cc 100644 --- a/package/editor/translations.json +++ b/package/editor/translations.json @@ -25,7 +25,39 @@ "wokrlie.git_integration.status_copied": "Copied", "wokrlie.git_integration.status_conflicted": "Conflicted", "wokrlie.git_integration.status_untracked": "Untracked", - "wokrlie.git_integration.status_ignored": "Ignored" + "wokrlie.git_integration.status_ignored": "Ignored", + "wokrlie.git_integration.detached_head": "detached HEAD", + "wokrlie.git_integration.no_branch": "(no branch)", + "wokrlie.git_integration.branches": "Branches", + "wokrlie.git_integration.branch_filter": "Filter branches...", + "wokrlie.git_integration.no_branches": "No branch matches the filter.", + "wokrlie.git_integration.selected_branch": "Selected", + "wokrlie.git_integration.select_a_branch": "Pick a branch in the list to use the actions below.", + "wokrlie.git_integration.checkout": "Checkout", + "wokrlie.git_integration.rename": "Rename", + "wokrlie.git_integration.rename_to": "New name...", + "wokrlie.git_integration.cancel": "Cancel", + "wokrlie.git_integration.delete": "Delete", + "wokrlie.git_integration.force_delete": "Force delete", + "wokrlie.git_integration.force_delete_hint": "Delete the branch even when it has commits that were never merged.", + "wokrlie.git_integration.new_branch_name": "New branch name...", + "wokrlie.git_integration.create_branch": "Create", + "wokrlie.git_integration.branch_log": "Branch log", + "wokrlie.git_integration.branch_log_empty": "This branch has no commits yet.", + "wokrlie.git_integration.branch_log_loading": "Loading the log...", + "wokrlie.git_integration.operation_failed": "Operation failed", + "wokrlie.git_integration.error_see_console": "The full message was written to the Console.", + "wokrlie.git_integration.open_console": "Open Console", + "wokrlie.git_integration.copy_details": "Copy details", + "wokrlie.git_integration.close": "Close", + "wokrlie.git_integration.error_local_changes": "Local changes would be overwritten by the switch. Commit or stash them first.", + "wokrlie.git_integration.error_branch_not_merged": "That branch has commits that were never merged. Force delete it if you are sure.", + "wokrlie.git_integration.error_delete_current": "That is the branch the project is on. Switch to another one first.", + "wokrlie.git_integration.error_branch_missing": "That branch does not exist any more.", + "wokrlie.git_integration.error_invalid_name": "That is not a valid branch name.", + "wokrlie.git_integration.error_branch_exists": "A branch with that name already exists.", + "wokrlie.git_integration.error_worktree": "That branch is already used by another worktree.", + "wokrlie.git_integration.error_generic": "The command failed. The details are in the Console." }, "zh": { "wokrlie.git_integration.menu_root": "Git 集成", @@ -51,7 +83,39 @@ "wokrlie.git_integration.status_copied": "已复制", "wokrlie.git_integration.status_conflicted": "存在冲突", "wokrlie.git_integration.status_untracked": "未跟踪", - "wokrlie.git_integration.status_ignored": "已忽略" + "wokrlie.git_integration.status_ignored": "已忽略", + "wokrlie.git_integration.detached_head": "分离 HEAD", + "wokrlie.git_integration.no_branch": "(无分支)", + "wokrlie.git_integration.branches": "分支", + "wokrlie.git_integration.branch_filter": "过滤分支…", + "wokrlie.git_integration.no_branches": "没有匹配的分支。", + "wokrlie.git_integration.selected_branch": "已选择", + "wokrlie.git_integration.select_a_branch": "在列表里选一个分支,下面的操作就会作用于它。", + "wokrlie.git_integration.checkout": "切换", + "wokrlie.git_integration.rename": "重命名", + "wokrlie.git_integration.rename_to": "新名字…", + "wokrlie.git_integration.cancel": "取消", + "wokrlie.git_integration.delete": "删除", + "wokrlie.git_integration.force_delete": "强制删除", + "wokrlie.git_integration.force_delete_hint": "即使分支还有从未合并的提交也删除。", + "wokrlie.git_integration.new_branch_name": "新分支名…", + "wokrlie.git_integration.create_branch": "创建", + "wokrlie.git_integration.branch_log": "分支日志", + "wokrlie.git_integration.branch_log_empty": "该分支还没有提交。", + "wokrlie.git_integration.branch_log_loading": "正在加载日志…", + "wokrlie.git_integration.operation_failed": "操作失败", + "wokrlie.git_integration.error_see_console": "完整信息已写入 Console。", + "wokrlie.git_integration.open_console": "打开 Console", + "wokrlie.git_integration.copy_details": "复制详情", + "wokrlie.git_integration.close": "关闭", + "wokrlie.git_integration.error_local_changes": "本地有未提交的修改,切换分支会覆盖它们。请先提交或暂存。", + "wokrlie.git_integration.error_branch_not_merged": "该分支还有从未合并的提交。确认不要了就强制删除。", + "wokrlie.git_integration.error_delete_current": "那是项目当前所在的分支。请先切到别的分支。", + "wokrlie.git_integration.error_branch_missing": "该分支已不存在。", + "wokrlie.git_integration.error_invalid_name": "这不是合法的分支名。", + "wokrlie.git_integration.error_branch_exists": "同名分支已存在。", + "wokrlie.git_integration.error_worktree": "该分支已被另一个 worktree 占用。", + "wokrlie.git_integration.error_generic": "命令执行失败,详情见 Console。" } } } diff --git a/package/editor/wokrlie/git_integration/git.py b/package/editor/wokrlie/git_integration/git.py new file mode 100644 index 0000000..229d32b --- /dev/null +++ b/package/editor/wokrlie/git_integration/git.py @@ -0,0 +1,487 @@ +"""Git command execution and output parsing for the Git panel. + +Every call to the ``git`` executable lives in this module. It never touches +the Engine API, so the panel can run it on a worker thread without any +Engine state involved. + +The status format is ``git status --porcelain=v2 -z --branch``: + +* ``-z`` keeps paths verbatim, so a file called ``名字 file.txt`` is not + escaped into ``"\\345\\220..."`` the way the older v1 format does. +* ``--branch`` adds the branch header lines, so the current branch, its + upstream, and the ahead/behind counts arrive with the file list instead + of costing another process launch. +""" + +from __future__ import annotations + +import subprocess +import threading +from dataclasses import dataclass, field +from typing import Any, Callable + + +#: Timeout for the read-only commands. +GIT_TIMEOUT = 15.0 +#: Timeout for the commands that rewrite the working tree. +MUTATION_TIMEOUT = 120.0 +#: Timeout for the branch name validation call. +VALIDATION_TIMEOUT = 10.0 +#: How many commits the branch log shows. +LOG_LIMIT = 50 + +#: ``for-each-ref`` format: refname, short name, upstream, current marker. +_BRANCH_FORMAT = "%(refname)%09%(refname:short)%09%(upstream:short)%09%(HEAD)" + + +@dataclass(frozen=True) +class CommandResult: + """The outcome of one git command.""" + + returncode: int + stdout: str = "" + stderr: str = "" + #: The command line that was run. The Console entry quotes it, so a + #: failure can be reproduced by hand. + command: str = "" + + @property + def ok(self) -> bool: + return self.returncode == 0 + + @property + def summary(self) -> str: + """One readable line describing a failure.""" + for text in (self.stderr, self.stdout): + for line in text.splitlines(): + message = line.strip() + if message: + return message + return f"exit code {self.returncode}" + + +@dataclass +class StatusSnapshot: + """The repository state as of one status call.""" + + staged: dict[str, str] = field(default_factory=dict) + unstaged: dict[str, str] = field(default_factory=dict) + untracked: list[str] = field(default_factory=list) + branch: str = "" + detached: bool = False + upstream: str = "" + ahead: int = 0 + behind: int = 0 + #: The commit HEAD points at, used to name a detached HEAD. + oid: str = "" + + @property + def change_count(self) -> int: + return len(self.unstaged) + len(self.untracked) + + +@dataclass(frozen=True) +class BranchInfo: + """One branch, local or remote.""" + + name: str + remote: bool = False + current: bool = False + upstream: str = "" + + +@dataclass(frozen=True) +class LogEntry: + """One commit in a branch log.""" + + sha: str + subject: str + + +@dataclass +class RepositoryState: + """What one background pass found out about the repository.""" + + #: Whether the folder is inside a work tree. + inside: bool + #: Whether git itself could be started at all. + available: bool = True + #: The file lists and the branch state, when they could be read. + snapshot: StatusSnapshot | None = None + #: The local and remote branches. + branches: list[BranchInfo] = field(default_factory=list) + #: The failure that stopped the pass, when there was one. + error: CommandResult | None = None + + +class GitRunner: + """Runs git commands against one repository.""" + + def __init__(self, cwd: str) -> None: + self.cwd = cwd + + def run(self, *args: str, timeout: float = GIT_TIMEOUT) -> CommandResult: + """Run one git command and capture its output. + + The output is decoded as UTF-8 on purpose. Branch names and file + paths are UTF-8 regardless of the system locale, and decoding them + with the locale encoding mangles them on a Windows that is not + running in UTF-8. + """ + command = "git " + " ".join(args) + try: + completed = subprocess.run( + ["git", *args], + cwd=self.cwd, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=timeout, + ) + except FileNotFoundError: + return CommandResult(127, "", "Git is not installed.", command) + except subprocess.TimeoutExpired: + return CommandResult( + 124, "", f"`{command}` timed out after {timeout:g}s.", command + ) + except OSError as exc: + return CommandResult(1, "", str(exc), command) + return CommandResult( + completed.returncode, completed.stdout, completed.stderr, command + ) + + +class GitCommand: + """One unit of work running on a worker thread. + + The thread only runs the callable and stores its result, so it never + touches Engine state and the render thread keeps drawing while a slow + ``git checkout`` works through a large repository. + """ + + def __init__(self, task: Callable[[], Any], name: str = "git-task") -> None: + self._task = task + self._name = name + self._result: Any = None + self._thread: threading.Thread | None = None + + @classmethod + def command( + cls, + runner: GitRunner, + args: tuple[str, ...], + timeout: float = GIT_TIMEOUT, + ) -> "GitCommand": + """Run one git command. + + *args* is the argument list of the command, for example + ``("checkout", "topic")``. The first argument also names the + worker thread, so a callable does not belong here. + """ + return cls(lambda: runner.run(*args, timeout=timeout), f"git {args[0]}") + + def start(self) -> None: + if self._thread is not None: + return + self._thread = threading.Thread( + target=self._run, name=self._name, daemon=True + ) + self._thread.start() + + def _run(self) -> None: + self._result = self._task() + + def poll(self) -> Any: + """Return the result once the work finished, otherwise ``None``.""" + return self._result + + @property + def running(self) -> bool: + return self._thread is not None and self._thread.is_alive() + + +# ---------------------------------------------------------------------- # +# 状态解析 +# ---------------------------------------------------------------------- # +def parse_status(payload: str) -> StatusSnapshot: + """Parse ``git status --porcelain=v2 -z --branch`` output. + + The entries are NUL separated. A rename carries its original path as a + second field, so the token stream has to be walked rather than split + into lines. + """ + snapshot = StatusSnapshot() + tokens = payload.split("\0") + index = 0 + while index < len(tokens): + token = tokens[index] + index += 1 + if not token: + continue + if token.startswith("# "): + _parse_header(token[2:], snapshot) + continue + kind = token[0] + if kind == "1": + fields = token.split(" ", 8) + if len(fields) >= 9: + _record(snapshot, fields[8], fields[1]) + elif kind == "2": + fields = token.split(" ", 9) + if len(fields) >= 10: + # The original path follows as its own NUL terminated field. + index += 1 + _record(snapshot, fields[9], fields[1]) + elif kind == "u": + fields = token.split(" ", 10) + if len(fields) >= 11: + _record(snapshot, fields[10], fields[1]) + elif kind == "?": + snapshot.untracked.append(token[2:]) + elif kind == "!": + continue + return snapshot + + +def _parse_header(header: str, snapshot: StatusSnapshot) -> None: + key, _, value = header.partition(" ") + if key == "branch.head": + if value == "(detached)": + snapshot.detached = True + else: + snapshot.branch = value + elif key == "branch.upstream": + snapshot.upstream = value + elif key == "branch.oid": + # ``(initial)`` marks a repository that has no commit yet. + if value and value != "(initial)": + snapshot.oid = value + elif key == "branch.ab": + parts = value.split() + if len(parts) == 2: + snapshot.ahead = _count(parts[0]) + snapshot.behind = _count(parts[1]) + + +def _count(value: str) -> int: + try: + return int(value.lstrip("+-")) + except ValueError: + return 0 + + +def _record(snapshot: StatusSnapshot, path: str, code: str) -> None: + """File one path under the staged and/or unstaged list. + + The two states are judged separately, so a file that is both staged and + modified again appears in both lists with its own status code. + + Porcelain v2 writes ``.`` where v1 wrote a space to mean "unchanged", + so both spellings are accepted here. + """ + index_status = code[0] if code else "." + worktree_status = code[1] if len(code) > 1 else "." + if index_status not in (".", " ", "?"): + snapshot.staged[path] = index_status + if worktree_status not in (".", " ", "?"): + snapshot.unstaged[path] = worktree_status + + +# ---------------------------------------------------------------------- # +# 查询 +# ---------------------------------------------------------------------- # +def read_status(runner: GitRunner) -> CommandResult: + """Collect the file lists and the branch state in one call.""" + return runner.run( + "status", "--porcelain=v2", "-z", "--branch", timeout=GIT_TIMEOUT + ) + + +def read_repository_state(runner: GitRunner) -> RepositoryState: + """Check whether the folder is a repository and read its state. + + The commands run back to back so the whole check costs one worker + thread instead of two. The branch list belongs to the same pass: it + comes from the refs, so it is cheap next to the status. + """ + inside = runner.run("rev-parse", "--is-inside-work-tree") + if inside.returncode == 127: + # The runner reports 127 when git could not be started at all. + return RepositoryState(inside=False, available=False, error=inside) + if not inside.ok or inside.stdout.strip() != "true": + return RepositoryState(inside=False, error=inside) + result = read_status(runner) + if not result.ok: + return RepositoryState(inside=True, error=result) + return RepositoryState( + inside=True, + snapshot=parse_status(result.stdout), + branches=list_branches(runner), + ) + + +def is_safe_branch_name(name: str) -> bool: + """Whether *name* can be handed to a git command without being read as an option. + + Git itself refuses to create a branch whose name starts with a dash, so + this only guards the names that come from somewhere else. + """ + text = name.strip() + return bool(text) and not text.startswith("-") + + +def list_branches(runner: GitRunner) -> list[BranchInfo]: + """Return the local and remote branches of the repository. + + ``git branch --list`` is not used here: its patterns do not match the + remote branches the way they are shown on screen, and its output is + not a stable machine format. ``for-each-ref`` states every field + explicitly. + """ + result = runner.run( + "for-each-ref", f"--format={_BRANCH_FORMAT}", "refs/heads/", "refs/remotes/" + ) + if not result.ok: + return [] + branches: list[BranchInfo] = [] + for line in result.stdout.splitlines(): + columns = line.split("\t") + if len(columns) < 4: + continue + refname, short, upstream, head = columns[:4] + if refname.startswith("refs/remotes/"): + # ``origin/HEAD`` is the symbolic pointer to the default branch, + # not a branch the user can switch to. + if refname.endswith("/HEAD"): + continue + branches.append(BranchInfo(short, remote=True, upstream=upstream)) + elif refname.startswith("refs/heads/"): + branches.append( + BranchInfo(short, current=(head == "*"), upstream=upstream) + ) + return branches + + +def read_log( + runner: GitRunner, ref: str, limit: int = LOG_LIMIT +) -> list[LogEntry]: + """The commits of a branch, newest first. + + The subject is separated from the hash with a tab, so a subject that + contains spaces cannot be mistaken for part of the hash. + """ + if not ref: + return [] + result = runner.run( + "log", + f"--max-count={limit}", + "--format=%h%x09%s", + ref, + timeout=GIT_TIMEOUT, + ) + if not result.ok: + return [] + entries: list[LogEntry] = [] + for line in result.stdout.splitlines(): + sha, _, subject = line.partition("\t") + if sha: + entries.append(LogEntry(sha, subject)) + return entries + + +def validate_branch_name(runner: GitRunner, name: str) -> str: + """Return the normalised branch name, or an empty string when Git refuses it. + + ``git check-ref-format --branch`` is the authority. It also rejects a + name that starts with a dash, which would otherwise be read as an + option by the command that creates it. + """ + text = name.strip() + if not text or text.startswith("-") or text == "HEAD" or text.startswith("@{"): + return "" + result = runner.run( + "check-ref-format", "--branch", text, timeout=VALIDATION_TIMEOUT + ) + if not result.ok: + return "" + return result.stdout.strip() + + +# ---------------------------------------------------------------------- # +# 操作 +# ---------------------------------------------------------------------- # +def checkout(runner: GitRunner, name: str) -> CommandResult: + """Switch to an existing branch.""" + return runner.run("checkout", name, timeout=MUTATION_TIMEOUT) + + +def create_branch(runner: GitRunner, name: str) -> CommandResult: + """Create a branch from the current HEAD and switch to it. + + The name is validated first, so the caller does not have to run a + second command of its own — and the validation does not happen on + the render thread. + + ``--`` is deliberately not used here: ``git checkout -- -b topic`` + switches pathspecs instead of creating a branch. + """ + valid = validate_branch_name(runner, name) + if not valid: + return CommandResult(1, "", f"`{name}` is not a valid branch name.") + return runner.run("checkout", "-b", valid, timeout=MUTATION_TIMEOUT) + + +def rename_branch(runner: GitRunner, old: str, new: str) -> CommandResult: + """Rename a local branch. + + The new name is validated the same way a new branch name is, so a + rename cannot smuggle a name past git that git would refuse. + """ + valid = validate_branch_name(runner, new) + if not valid: + return CommandResult(1, "", f"`{new}` is not a valid branch name.") + return runner.run("branch", "-m", old, valid, timeout=MUTATION_TIMEOUT) + + +def delete_branch( + runner: GitRunner, name: str, force: bool = False +) -> CommandResult: + """Delete a local branch. + + Without *force* git refuses to delete a branch whose commits were + never merged into the current branch or into its upstream. + """ + return runner.run( + "branch", "-D" if force else "-d", name, timeout=MUTATION_TIMEOUT + ) + + +def stage_file(runner: GitRunner, path: str) -> CommandResult: + """Stage one file, including a deletion.""" + return runner.run("add", "--", path, timeout=MUTATION_TIMEOUT) + + +def stage_all(runner: GitRunner) -> CommandResult: + """Stage every change, the same as ``git add -A``.""" + return runner.run("add", "-A", timeout=MUTATION_TIMEOUT) + + +def unstage_file(runner: GitRunner, path: str) -> CommandResult: + """Unstage one file. + + ``git reset HEAD -- `` unstages the file in both cases: in a + repository that has no commit yet, git falls back to the empty tree + and the file returns to being untracked. + """ + return runner.run("reset", "HEAD", "--", path, timeout=MUTATION_TIMEOUT) + + +def commit(runner: GitRunner, message: str) -> CommandResult: + """Create a commit from the staged changes.""" + return runner.run("commit", "-m", message, timeout=MUTATION_TIMEOUT) + + +def init_repository(runner: GitRunner) -> CommandResult: + """Create a repository in the folder.""" + return runner.run("init", timeout=MUTATION_TIMEOUT) diff --git a/package/editor/wokrlie/git_integration/icons.py b/package/editor/wokrlie/git_integration/icons.py index 6596146..e8f3387 100644 --- a/package/editor/wokrlie/git_integration/icons.py +++ b/package/editor/wokrlie/git_integration/icons.py @@ -6,6 +6,11 @@ reproduced in ``package/plugin_pages/license.md``, which ships inside the plugin archive as the plugin's License page. +Three of the icons are geometrically identical to the Feather icons of the +same name and therefore stay under the Feather MIT License: the stage button +(``plus``), the unstage button (``minus``), and ``chevron-down``. That notice +is reproduced on the same licence page. + Every icon is stored as the inner markup of a 24x24 Lucide SVG. They are rasterized at runtime through the Engine's LunaSVG backend and uploaded as pinned ImGui textures, so one vector asset can be drawn in any colour without @@ -40,6 +45,12 @@ '' '' ), + "git-branch": ( + '' + '' + '' + ), + "chevron-down": '', # -- file status ---------------------------------------------------- "added": ( '' diff --git a/package/editor/wokrlie/git_integration/panel.py b/package/editor/wokrlie/git_integration/panel.py index 82f8a79..e23547f 100644 --- a/package/editor/wokrlie/git_integration/panel.py +++ b/package/editor/wokrlie/git_integration/panel.py @@ -3,7 +3,6 @@ from __future__ import annotations import os -import subprocess import time from infernux import Debug @@ -14,9 +13,54 @@ from infernux.engine.ui.panel_registry import editor_panel from infernux.engine.ui.theme import ImGuiCol +from .git import ( + BranchInfo, + CommandResult, + GitCommand, + GitRunner, + LogEntry, + StatusSnapshot, + checkout, + commit, + create_branch, + delete_branch, + init_repository, + is_safe_branch_name, + read_log, + read_repository_state, + rename_branch, + stage_all, + stage_file, + unstage_file, +) from .icons import IconCache, NEUTRAL_COLOR, STATUS_COLORS, STATUS_LABELS +#: Longest branch name shown in the header before it is shortened. +_MAX_BRANCH_LABEL = 28 +#: Longest commit subject shown in the branch log before it is shortened. +_MAX_SUBJECT = 72 +#: Dimmed colour for secondary text such as the upstream of a branch. +_DIM_COLOR = (0.55, 0.55, 0.58, 1.0) +#: Colour of the branch name while HEAD is detached. +_DETACHED_COLOR = (0.95, 0.55, 0.20, 1.0) +#: ImGui's ``ImGuiCond_FirstUseEver``. A section opens the first time the +#: user sees it and then keeps whatever state they leave it in. +_FIRST_USE = 4 + + +def _shorten(text: str) -> str: + """Cut a long text down to the width the panel can show. + + A commit subject is a single line, and a line that runs past the edge + of the panel is cut off by ImGui without any hint, so the tail is + dropped here instead. + """ + if len(text) <= _MAX_SUBJECT: + return text + return text[: _MAX_SUBJECT - 1] + "…" + + @editor_panel( "Git Integration", type_id="wokrlie.git_integration", @@ -29,7 +73,17 @@ interaction=PanelInteractionDescriptor(), ) class GitIntegrationPanel(EditorPanel): - """Source control panel backed by the ``git`` command line.""" + """Source control panel backed by the ``git`` command line. + + Every git command runs on a worker thread. The render thread only + draws the last snapshot it received, so a slow repository never + freezes the Editor. + """ + + #: Tag for the Console entries this plugin writes. The Engine groups and + #: clears entries by source, so the plugin's diagnostics stay separable + #: from everyone else's. + SOURCE_FILE = "wokrlie/git_integration/panel.py" def __init__(self) -> None: super().__init__("Git Integration", "wokrlie.git_integration.panel") @@ -37,17 +91,33 @@ def __init__(self) -> None: self.have_git: bool = False self.is_repo_initialized: bool = False - # ``staged_files``/``unstaged_files`` map a path to its porcelain status - # code. A path may appear in both when it has staged *and* unstaged - # content (for example the ``AM`` state). - self.staged_files: dict[str, str] = {} - self.unstaged_files: dict[str, str] = {} - self.untracked_files: list[str] = [] + self._snapshot = StatusSnapshot() + self._state_known: bool = False + self._status_command: GitCommand | None = None + self._action_command: GitCommand | None = None + self._action_report: bool = False + self._action_on_success = None + + self._branches: list[BranchInfo] = [] + self._branch_filter: str = "" + self._new_branch: str = "" + self._selected_branch: str = "" + self._rename_open: bool = False + self._rename_name: str = "" + + self._log_branch: str = "" + self._log_request: str = "" + self._log_entries: list[LogEntry] = [] + self._log_command: GitCommand | None = None + + self._error: str = "" + self._error_detail: str = "" + self._error_shown: bool = False + self._copy_requested: bool = False self._commit_message: str = "" self._last_refresh: float = 0.0 self._refresh_interval: float = 1.0 - self._git_checked: bool = False self._icons: IconCache | None = None self._icon_size: float = 16.0 @@ -57,12 +127,26 @@ def __init__(self) -> None: # 生命周期(保持惰性初始化,避免 on_enable 崩溃) # ------------------------------------------------------------------ # def on_enable(self) -> None: - self._git_checked = False self.have_git = False self.is_repo_initialized = False - self.staged_files = {} - self.unstaged_files = {} - self.untracked_files = [] + self._snapshot = StatusSnapshot() + self._state_known = False + self._status_command = None + self._action_command = None + self._branches = [] + self._branch_filter = "" + self._new_branch = "" + self._selected_branch = "" + self._rename_open = False + self._rename_name = "" + self._log_branch = "" + self._log_request = "" + self._log_entries = [] + self._log_command = None + self._error = "" + self._error_detail = "" + self._error_shown = False + self._last_refresh = 0.0 @property def repo_path(self) -> str: @@ -74,6 +158,23 @@ def repo_path(self) -> str: """ return get_project_root() or os.getcwd() + def _runner(self) -> GitRunner: + """A runner bound to the folder the panel currently works on.""" + return GitRunner(self.repo_path) + + # ------------------------------------------------------------------ # + # 日志(写入引擎 Console) + # ------------------------------------------------------------------ # + def _log_error(self, message: str) -> None: + """Write one error to the Editor Console. + + The Console keeps the entry after the panel closes, so a long Git + message stays readable and can be copied from there. A panel popup + only points the user here; it is not the place where the error + survives. + """ + Debug.log_error(message, source_file=self.SOURCE_FILE) + # ------------------------------------------------------------------ # # 图标(Lucide SVG → 运行时光栅化 → ImGui 纹理) # ------------------------------------------------------------------ # @@ -124,21 +225,22 @@ def _icon_button(self, ctx, widget_id: str, icon: str, tooltip: str, on_click) - on_click() self._tooltip(ctx, tooltip) + # ------------------------------------------------------------------ # + # 渲染主流程 + # ------------------------------------------------------------------ # def on_render_content(self, ctx) -> None: - if not self._git_checked: - self._check_git_availability() - self._git_checked = True + self._poll_background() + self._schedule_status() + + if not self._state_known: + # The first status call has not answered yet. Whether git is + # usable at all is answered by the same call. + return if not self.have_git: ctx.label(t("wokrlie.git_integration.git_unavailable")) 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 @@ -169,6 +271,8 @@ def _render_git_ui(self, ctx) -> None: self._manual_refresh, ) + self._render_branches_section(ctx) + ctx.begin_group("Changes") try: self._render_staged_section(ctx) @@ -193,6 +297,370 @@ def _render_git_ui(self, ctx) -> None: finally: ctx.end_group() + self._render_error_dialog(ctx) + + # ------------------------------------------------------------------ # + # 分支 + # ------------------------------------------------------------------ # + def _render_branches_section(self, ctx) -> None: + """The branch section: the current branch, the list, and the new row. + + The branches live in their own section instead of behind a popup: + the list is the thing the user works with, and a popup hid it + behind one click. + """ + ctx.set_next_item_open(True, _FIRST_USE) + if not ctx.collapsing_header( + f"{t('wokrlie.git_integration.branches')} ({len(self._branches)})###branches" + ): + return + + self._render_current_branch(ctx) + ctx.separator() + + ctx.set_next_item_width(280.0) + self._branch_filter = ctx.input_text_with_hint( + "##git_branch_filter", + t("wokrlie.git_integration.branch_filter"), + self._branch_filter, + 128, + ) + + labels, entries = self._visible_branches() + if labels: + clicked = ctx.selectable_list_clipped(labels) + if 0 <= clicked < len(entries): + self._select_branch(entries[clicked]) + else: + ctx.label(t("wokrlie.git_integration.no_branches")) + + ctx.separator() + self._render_branch_actions(ctx) + self._render_branch_log(ctx) + ctx.separator() + self._render_create_branch(ctx) + + def _select_branch(self, branch: BranchInfo) -> None: + """Remember which branch the actions below the list apply to. + + The list does not switch on a click any more: the actions need a + target, and the branch the project is on cannot be deleted. + """ + if self._selected_branch == branch.name: + return + self._selected_branch = branch.name + self._rename_open = False + self._rename_name = "" + # The log on screen belongs to the branch that was selected before, + # so it goes away instead of being shown under the new name. + self._log_branch = "" + self._log_entries = [] + + def _render_branch_actions(self, ctx) -> None: + """The actions that apply to the selected branch.""" + name = self._selected_branch + if not name: + ctx.label(t("wokrlie.git_integration.select_a_branch")) + return + + ctx.label(f"{t('wokrlie.git_integration.selected_branch')}: {name}") + + ctx.button( + t("wokrlie.git_integration.checkout"), + lambda: self._checkout_selected(name), + 90.0, + 0.0, + ) + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.rename"), + self._open_rename, + 90.0, + 0.0, + ) + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.delete"), + lambda: self._delete_branch(name, False), + 90.0, + 0.0, + ) + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.force_delete"), + lambda: self._delete_branch(name, True), + 110.0, + 0.0, + ) + self._tooltip(ctx, t("wokrlie.git_integration.force_delete_hint")) + + if self._rename_open: + self._render_rename_row(ctx, name) + + def _render_rename_row(self, ctx, name: str) -> None: + """The row that renames the selected branch.""" + ctx.set_next_item_width(200.0) + self._rename_name = ctx.input_text_with_hint( + "##git_rename_branch", + t("wokrlie.git_integration.rename_to"), + self._rename_name, + 128, + ) + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.rename"), + lambda: self._rename_branch(name), + 90.0, + 0.0, + ) + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.cancel"), + self._close_rename, + 90.0, + 0.0, + ) + + def _render_branch_log(self, ctx) -> None: + """The commit log of the selected branch. + + The log is fetched in the background, so a branch with a long + history does not stall the frame. + """ + name = self._selected_branch + if not name: + return + self._request_log(name) + + ctx.set_next_item_open(True, _FIRST_USE) + if not ctx.collapsing_header( + f"{t('wokrlie.git_integration.branch_log')} " + f"({len(self._log_entries)})###branch_log" + ): + return + + if not self._log_entries: + if self._log_command is not None: + ctx.label(t("wokrlie.git_integration.branch_log_loading")) + else: + ctx.label(t("wokrlie.git_integration.branch_log_empty")) + return + + for entry in self._log_entries: + ctx.push_style_color(ImGuiCol.Text, *_DIM_COLOR) + ctx.label(entry.sha) + ctx.pop_style_color() + ctx.same_line() + ctx.label(_shorten(entry.subject)) + + def _request_log(self, name: str) -> None: + """Ask for the log of a branch when it is not on screen yet.""" + if self._log_command is not None or not name: + return + if self._log_branch == name: + # The log of this branch is already here. A branch without any + # commit has an empty log, and asking again every frame would + # start a git process per frame. + return + runner = self._runner() + self._log_request = name + self._log_command = GitCommand(lambda: read_log(runner, name), "git log") + self._log_command.start() + + def _open_rename(self) -> None: + """Show the row that renames the selected branch.""" + self._rename_open = True + + def _close_rename(self) -> None: + """Hide the rename row again.""" + self._rename_open = False + self._rename_name = "" + + def _checkout_selected(self, name: str) -> None: + """Switch to the selected branch.""" + for branch in self._branch_rows(): + if branch.name == name: + self._switch_to(branch) + return + self._report_failure( + t("wokrlie.git_integration.error_branch_missing"), name + ) + + def _rename_branch(self, name: str) -> None: + """Rename the selected branch.""" + new_name = self._rename_name.strip() + if not new_name: + self._report_failure( + t("wokrlie.git_integration.error_invalid_name"), + "A new branch name is needed.", + ) + return + runner = self._runner() + self._start_action( + lambda: rename_branch(runner, name, new_name), + report=True, + on_success=lambda: self._adopt_renamed_branch(name, new_name), + ) + self._close_rename() + + def _delete_branch(self, name: str, force: bool) -> None: + """Delete the selected branch.""" + runner = self._runner() + self._start_action( + lambda: delete_branch(runner, name, force), + report=True, + on_success=lambda: self._forget_branch(name), + ) + + def _adopt_renamed_branch(self, old: str, new: str) -> None: + """Follow the branch that was renamed. + + The branch list still holds the old name until the next status + pass, so the selection is moved over by hand. Otherwise the + actions would keep aiming at a branch that no longer exists. + """ + if self._selected_branch == old: + self._selected_branch = new + self._log_branch = "" + self._log_entries = [] + + def _forget_branch(self, name: str) -> None: + """Drop a branch that was deleted from the panel state.""" + if self._selected_branch == name: + self._selected_branch = "" + self._rename_open = False + self._rename_name = "" + self._log_branch = "" + self._log_entries = [] + + def _render_current_branch(self, ctx) -> None: + """The branch the project is on, with its upstream and its drift.""" + icon = self._icon("git-branch") + if icon: + ctx.image(icon, self._icon_size, self._icon_size) + ctx.same_line() + + name = self._branch_label() + detached = self._snapshot.detached + if detached: + ctx.push_style_color(ImGuiCol.Text, *_DETACHED_COLOR) + ctx.label(name) + if detached: + ctx.pop_style_color() + self._tooltip(ctx, self._branch_tooltip()) + + if self._snapshot.upstream: + ctx.same_line() + ctx.push_style_color(ImGuiCol.Text, *_DIM_COLOR) + ctx.label(self._upstream_label()) + ctx.pop_style_color() + + def _branch_label(self) -> str: + """The branch name shown in the header.""" + if self._snapshot.detached: + return t("wokrlie.git_integration.detached_head") + name = self._snapshot.branch + if not name: + return t("wokrlie.git_integration.no_branch") + if len(name) > _MAX_BRANCH_LABEL: + return name[: _MAX_BRANCH_LABEL - 1] + "…" + return name + + def _branch_tooltip(self) -> str: + """The full branch name, for when the header shortens it.""" + if self._snapshot.detached: + label = t("wokrlie.git_integration.detached_head") + sha = self._snapshot.oid[:7] + return f"{label} {sha}" if sha else label + return self._snapshot.branch or t("wokrlie.git_integration.no_branch") + + def _upstream_label(self) -> str: + """The upstream of the current branch and how far it drifted.""" + text = self._snapshot.upstream + if self._snapshot.ahead or self._snapshot.behind: + text = f"{text} ↑{self._snapshot.ahead} ↓{self._snapshot.behind}" + return text + + def _visible_branches(self) -> tuple[list[str], list[BranchInfo]]: + """The branch rows that pass the filter, with the branch behind each.""" + needle = self._branch_filter.strip().casefold() + labels: list[str] = [] + entries: list[BranchInfo] = [] + for branch in self._branch_rows(): + if needle and needle not in branch.name.casefold(): + continue + marker = "" + if branch.name == self._selected_branch: + marker += "▸" + if branch.current: + marker += "●" + label = f"{marker} {branch.name}" if marker else branch.name + if branch.upstream: + label = f"{label} {branch.upstream}" + labels.append(label) + entries.append(branch) + return labels, entries + + def _branch_rows(self) -> list[BranchInfo]: + """Every branch to offer, with the current one always present. + + A repository without any commit has no branch ref yet, so the + current branch has to be added by hand. + """ + branches = list(self._branches) + current = self._snapshot.branch + if current and not any( + branch.name == current and not branch.remote for branch in branches + ): + branches.insert(0, BranchInfo(current, current=True)) + return branches + + def _render_create_branch(self, ctx) -> None: + """The row that creates a branch from the current HEAD.""" + ctx.set_next_item_width(280.0) + self._new_branch = ctx.input_text_with_hint( + "##git_new_branch", + t("wokrlie.git_integration.new_branch_name"), + self._new_branch, + 128, + ) + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.create_branch"), + self._create_branch, + 110.0, + 0.0, + ) + + def _switch_to(self, branch: BranchInfo) -> None: + """Start a switch to another branch.""" + if branch.current: + return + if not is_safe_branch_name(branch.name): + self._report_failure( + t("wokrlie.git_integration.error_invalid_name"), + f"`git checkout {branch.name}` is not a valid branch name.", + ) + return + name = branch.name + runner = self._runner() + self._start_action(lambda: checkout(runner, name), report=True) + + def _create_branch(self) -> None: + """Create a branch from the current HEAD and switch to it.""" + name = self._new_branch.strip() + if not name: + self._report_failure( + t("wokrlie.git_integration.error_invalid_name"), + "A branch name is needed.", + ) + return + runner = self._runner() + self._start_action(lambda: create_branch(runner, name), report=True) + + # ------------------------------------------------------------------ # + # 文件列表 + # ------------------------------------------------------------------ # def _render_file_row(self, ctx, path: str, status: str, staged: bool) -> None: """Render one file row: status icon, path, coloured code, action button. @@ -236,22 +704,25 @@ def _render_file_row(self, ctx, path: str, status: str, staged: bool) -> None: ) def _render_staged_section(self, ctx) -> None: + staged = self._snapshot.staged expanded = ctx.collapsing_header( f"{t('wokrlie.git_integration.staged_changes')} " - f"({len(self.staged_files)})###staged_changes" + f"({len(staged)})###staged_changes" ) if not expanded: return - if not self.staged_files: + if not staged: ctx.label(f" {t('wokrlie.git_integration.none')}") return - for path, status in sorted(self.staged_files.items()): + for path, status in sorted(staged.items()): self._render_file_row(ctx, path, status, staged=True) def _render_changes_section(self, ctx) -> None: - total = len(self.unstaged_files) + len(self.untracked_files) + unstaged = self._snapshot.unstaged + untracked = self._snapshot.untracked + total = len(unstaged) + len(untracked) expanded = ctx.collapsing_header( f"{t('wokrlie.git_integration.changes')} ({total})###changes" ) @@ -276,169 +747,293 @@ def _render_changes_section(self, ctx) -> None: ctx.label(f" {t('wokrlie.git_integration.none')}") return - for path, status in sorted(self.unstaged_files.items()): + for path, status in sorted(unstaged.items()): self._render_file_row(ctx, path, status, staged=False) - for path in sorted(self.untracked_files): + for path in sorted(untracked): self._render_file_row(ctx, path, "?", staged=False) # ------------------------------------------------------------------ # # 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 _report_git_missing(self) -> None: + """Record that git could not be started at all.""" + self.have_git = False + self._log_error("Git is not usable in current environment.") # ------------------------------------------------------------------ # - # 刷新:先检测仓库是否存在,再拉取文件状态 + # 后台执行 # ------------------------------------------------------------------ # - def refresh_git_status(self) -> None: - """Run `git status --porcelain` and rebuild the three file lists. + def _schedule_status(self) -> None: + """Start a status refresh when the previous one is done and due.""" + if self._status_command is not None or self._action_command is not None: + return + if self._state_known and not self.have_git: + # Git could not be started. Trying again would only spawn a + # process that cannot start. + return + now = time.time() + if now - self._last_refresh < self._refresh_interval: + return + self._last_refresh = now + self._start_status_refresh() - - ``AM path`` 这类文件会**同时**出现在 staged 和 unstaged 两个列表中, - 与 `git status` / VSCode 的显示一致。 + def _start_status_refresh(self) -> None: + """Ask the worker thread for the current repository state.""" + if self._status_command is not None: + return + runner = self._runner() + self._status_command = GitCommand( + lambda: read_repository_state(runner), "git status" + ) + self._status_command.start() + + def _start_action( + self, + job, + report: bool = False, + on_success=None, + ) -> None: + """Start one mutating git job in the background. + + *job* is a callable that runs the command and returns its + result. It runs on a worker thread, so it must not touch the + Engine API: the runner it needs is captured on the render thread + before the job is handed over. + + *report* turns a failure into the modal dialog; the routine + operations only write to the Console. """ - 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 = [] + if self._action_command is not None: 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}") + self._action_report = report + self._action_on_success = on_success + self._action_command = GitCommand(job, "git action") + self._action_command.start() + + def _poll_background(self) -> None: + """Apply the results of the background work that finished.""" + action = self._action_command + if action is not None: + result = action.poll() + if result is not None: + self._action_command = None + self._finish_action(result) + + status = self._status_command + if status is not None: + state = status.poll() + if state is not None: + self._status_command = None + self._apply_state(state) + + log = self._log_command + if log is not None: + entries = log.poll() + if entries is not None: + self._log_command = None + self._apply_log(entries) + + def _apply_log(self, entries: list[LogEntry]) -> None: + """Store the log the worker thread reported.""" + request = self._log_request + self._log_request = "" + if request != self._selected_branch: + # The selection changed while the log was loading. The next + # frame asks for the log of the branch that is selected now. + self._log_branch = "" + self._log_entries = [] + return + self._log_branch = request + self._log_entries = entries + + def _apply_state(self, state) -> None: + """Store the repository state the worker thread reported.""" + self._state_known = True + self.have_git = state.available + self.is_repo_initialized = state.inside + if state.snapshot is not None: + self._snapshot = state.snapshot + if state.inside: + self._branches = state.branches + elif not state.available: + self._report_git_missing() + elif state.error is not None: + self._log_error(f"`git status` failed: {state.error.summary}") + + def _finish_action(self, result: CommandResult) -> None: + """Apply the outcome of a mutating command.""" + if result.ok: + if self._action_on_success is not None: + self._action_on_success() + self._action_on_success = None + self._after_mutation() 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] + detail = (result.stderr or result.stdout).strip() + self._log_error(self._failure_report(result, detail)) + if self._action_report: + self._error = self._describe_failure(result) + self._error_detail = detail - if index_status == "?" and worktree_status == "?": - untracked.append(path) - continue + def _failure_report(self, result: CommandResult, detail: str) -> str: + """The full failure text, as the Console keeps it. - if index_status == "!" and worktree_status == "!": - continue + The command line, the exit code, and Git's own message all belong + here. The dialog in the panel only points at this entry, so this is + the one place where the reason survives. + """ + command = result.command or "git" + headline = f"`{command}` failed with exit code {result.returncode}" + return f"{headline}:\n{detail}" if detail else headline + + def _after_mutation(self) -> None: + """Ask for a fresh state after a mutating command finished.""" + self._last_refresh = 0.0 + # A commit lands on the branch that was selected, so the log that + # is on screen is one commit behind now. + self._log_branch = "" + + def _describe_failure(self, result: CommandResult) -> str: + """Turn a git failure into a message the user can act on. + + The wording of git's own messages differs between versions — an + older git says ``Cannot delete branch 'x' checked out at ...`` + where a newer one says ``cannot delete branch 'x' used by + worktree at ...`` — so the text is matched in lower case. + """ + text = f"{result.stderr}\n{result.stdout}" + lowered = text.lower() + if "would be overwritten by checkout" in lowered: + return t("wokrlie.git_integration.error_local_changes") + if "not fully merged" in lowered: + return t("wokrlie.git_integration.error_branch_not_merged") + if "delete branch" in lowered: + return t("wokrlie.git_integration.error_delete_current") + if "pathspec" in lowered or "did not match any file" in lowered: + return t("wokrlie.git_integration.error_branch_missing") + if "not found" in lowered: + return t("wokrlie.git_integration.error_branch_missing") + if "not a valid branch name" in lowered: + return t("wokrlie.git_integration.error_invalid_name") + if "already exists" in lowered: + return t("wokrlie.git_integration.error_branch_exists") + if "already used by worktree" in lowered: + return t("wokrlie.git_integration.error_worktree") + return t("wokrlie.git_integration.error_generic") - # 关键:X 和 Y 独立判断,不再互斥 - if index_status not in (" ", "?"): - staged[path] = index_status - if worktree_status not in (" ", "?"): - unstaged[path] = worktree_status + # ------------------------------------------------------------------ # + # 错误弹窗(Console 留档 + 弹窗指路) + # ------------------------------------------------------------------ # + def _report_failure(self, summary: str, detail: str = "") -> None: + """Show a failure in the panel and keep the full text in the Console.""" + self._log_error(detail or summary) + self._error = summary + self._error_detail = detail or summary + + def _render_error_dialog(self, ctx) -> None: + """The dialog that points at the Console for the full message.""" + if not self._error: + return - self.staged_files = staged - self.unstaged_files = unstaged - self.untracked_files = untracked + title = t("wokrlie.git_integration.operation_failed") + if not self._error_shown: + # Keep asking until ImGui accepts the request: a one frame + # request can be lost during focus arbitration. + ctx.open_popup(title) + + if not ctx.begin_popup_modal(title): + if self._error_shown: + # The user closed the modal. + self._error_shown = False + self._error = "" + self._error_detail = "" + return - def _is_inside_work_tree(self) -> bool: - """使用 `git rev-parse --is-inside-work-tree` 判断是否在 Git 工作树中。""" + self._error_shown = True try: - result = subprocess.run( - ["git", "rev-parse", "--is-inside-work-tree"], - capture_output=True, - text=True, - cwd=self.repo_path, - timeout=5, + ctx.text_wrapped(self._error) + ctx.text_wrapped(t("wokrlie.git_integration.error_see_console")) + ctx.separator() + ctx.button( + t("wokrlie.git_integration.open_console"), + self._open_console, + 150.0, + 0.0, + ) + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.copy_details"), + self._request_copy, + 150.0, + 0.0, ) - return result.returncode == 0 and result.stdout.strip() == "true" - except (FileNotFoundError, subprocess.TimeoutExpired): - return False + ctx.same_line() + ctx.button( + t("wokrlie.git_integration.close"), + self._dismiss_error, + 90.0, + 0.0, + ) + if self._copy_requested: + self._copy_requested = False + ctx.set_clipboard_text(self._error_detail) + finally: + ctx.end_popup() + + def _open_console(self) -> None: + """Focus the Engine Console so the full message can be read there.""" + try: + services = self.services + manager = services.window_manager if services is not None else None + if manager is None: + return + manager.open_window("console") + manager.focus_window("console") + except Exception as exc: # noqa: BLE001 - the panel must never fail + self._log_error(f"Cannot open the Console: {exc}") + + def _request_copy(self) -> None: + """Ask for the error text to be copied to the clipboard.""" + self._copy_requested = True + + def _dismiss_error(self) -> None: + """Close the error dialog.""" + self._error = "" + self._error_detail = "" # ------------------------------------------------------------------ # - # 初始化仓库 + # 仓库操作 # ------------------------------------------------------------------ # def init_git_repo(self) -> None: """在当前项目目录初始化一个新的 Git 仓库。""" folder = self.repo_path if not os.path.isdir(folder): - Debug.error(f"Cannot initialise a repository in a missing folder: {folder}") - return - - try: - result = subprocess.run( - ["git", "init"], - capture_output=True, - text=True, - cwd=folder, - timeout=10, + self._log_error( + f"Cannot initialise a repository in a missing folder: {folder}" ) - except FileNotFoundError: - Debug.error("Git is not installed.") - return - except subprocess.TimeoutExpired: - Debug.error("`git init` timed out.") return + self._start_action(lambda: init_repository(self._runner())) - 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.") + self._log_error("Commit message is empty.") return if not self.is_repo_initialized: - Debug.error("No Git repository. Please create one first.") + self._log_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 + message = msg + runner = self._runner() + self._start_action( + lambda: commit(runner, message), + on_success=self._clear_commit_message, + ) - 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 _clear_commit_message(self) -> None: + """Empty the message box after a successful commit, as VS Code does.""" + self._commit_message = "" def stage_file(self, path: str) -> None: """暂存单个文件(包括新增、修改、删除)。 @@ -447,82 +1042,25 @@ def stage_file(self, path: str) -> None: 同样会记录删除操作(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()}") + runner = self._runner() + self._start_action(lambda: stage_file(runner, path)) 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()}") + runner = self._runner() + self._start_action(lambda: stage_all(runner)) 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()}") + runner = self._runner() + self._start_action(lambda: unstage_file(runner, path)) # ------------------------------------------------------------------ # # 刷新辅助 # ------------------------------------------------------------------ # - 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.time() + self._last_refresh = 0.0 diff --git a/package/inx_package.json b/package/inx_package.json index 372ec08..9f5fc70 100644 --- a/package/inx_package.json +++ b/package/inx_package.json @@ -2,10 +2,10 @@ "$schema": "infernux.inxpackage.source", "reference": "wokrlie/git_integration", "name": "Git Integration", - "version": "0.1.5", + "version": "0.2.1", "engine": ">=0.4.1,<0.5", - "intro": "Git source control for the Infernux Engine: stage, unstage, and commit straight from the editor.", + "intro": "Git source control for the Infernux Engine: stage, unstage, commit, and switch, rename, or delete branches straight from the editor.", "intros": { - "zh-CN": "Infernux 引擎的 Git 源代码管理面板:直接在编辑器里暂存、取消暂存和提交。" + "zh-CN": "Infernux 引擎的 Git 源代码管理面板:直接在编辑器里暂存、取消暂存、提交,以及切换、重命名或删除分支。" } } diff --git a/package/plugin_pages/license.md b/package/plugin_pages/license.md index 6d0552f..30beed3 100644 --- a/package/plugin_pages/license.md +++ b/package/plugin_pages/license.md @@ -54,7 +54,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ### Feather Icons -Two of the icons used by the panel — `plus` and `minus` — are derived from the Feather project and are covered by the MIT License reproduced below. Every other icon is original Lucide artwork under the ISC License above. +Three of the icons used by the panel are derived from the Feather project and are covered by the MIT License reproduced below: the stage button, whose geometry is the Feather `plus` icon; the unstage button, whose geometry is the Feather `minus` icon; and the `chevron-down` arrow next to the branch name. Every other icon is original Lucide artwork under the ISC License above. ``` The MIT License (MIT) diff --git a/package/plugin_pages/license.zh-CN.md b/package/plugin_pages/license.zh-CN.md index 2532082..51b7e5e 100644 --- a/package/plugin_pages/license.zh-CN.md +++ b/package/plugin_pages/license.zh-CN.md @@ -56,7 +56,7 @@ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ### Feather Icons -面板用到的两个图标 —— `plus` 和 `minus` —— 派生自 Feather 项目,采用下面的 MIT License。其余图标均为 Lucide 原创作品,采用上面的 ISC License。 +面板用到的三个图标派生自 Feather 项目,采用下面的 MIT License:暂存按钮,其几何与 Feather 的 `plus` 图标一致;取消暂存按钮,其几何与 Feather 的 `minus` 图标一致;以及分支名旁边的 `chevron-down` 下拉箭头。其余图标均为 Lucide 原创作品,采用上面的 ISC License。 ``` The MIT License (MIT) diff --git a/package/plugin_pages/usage.md b/package/plugin_pages/usage.md index a8f4519..2a5e4e4 100644 --- a/package/plugin_pages/usage.md +++ b/package/plugin_pages/usage.md @@ -14,9 +14,10 @@ Git must be installed and reachable on your `PATH`. When it is not, the panel sh ## The panel layout -The normal view has four parts, from top to bottom: +The normal view has five parts, from top to bottom: - **Source Control** — the header. The refresh icon on the right forces an immediate `git status`, skipping the refresh interval. +- **Branches** — the branch the project is on, the list of branches, the actions that apply to the selected one, its commit log, and the row that creates a new branch. - **Staged Changes** — files that will be included in the next commit. - **Changes** — files that have been modified or deleted but are not staged yet, plus untracked files. - **Commit area** — a message box and a **Commit** button. @@ -51,6 +52,25 @@ At the end of the row sits the action button for that file. The panel updates the file lists automatically, at most once per second. If you want to see the current state immediately — for example after running Git commands in a terminal — click the refresh icon in the header. +## Managing branches + +The **Branches** section of the panel holds everything about branches. It opens the first time you open the panel, and you can fold it away like the file lists. + +- The first line is the branch the project is currently on, together with its upstream and how far it has drifted from it (`↑2 ↓1`). +- The list below shows the local branches first and the remote ones after them. The current branch is marked with a dot, and a branch that tracks another one shows its upstream on the right. +- Type in the filter box to narrow the list down. The filter only changes what is shown; it runs no command. +- Click a branch to select it. The selected branch is marked with an arrow, and the actions below the list apply to it. +- **Checkout** switches to the selected branch. The switch runs in the background, so the panel stays responsive even in a large repository. +- **Rename** opens a field for the new name. The name is checked before it is used, and a branch name may contain `/`, for example `feature/new-panel`. +- **Delete** removes the selected branch. Git refuses to delete a branch whose commits were never merged; **Force delete** removes it anyway, and the commits stay in git's reflog. +- Type a name in the field at the bottom and click **Create** to make a branch from the current commit and switch to it. + +### The branch log + +Under the actions sits the **Branch log**, which lists the commits of the selected branch, newest first. Every row shows the short hash of the commit and its subject. The log holds the last 50 commits and is fetched in the background, so a branch with a long history does not slow the panel down. It is fetched again after every commit, so a commit you just made shows up right away. + +If a switch fails — usually because the working tree has changes that the other branch would overwrite — a dialog explains what went wrong in one sentence and points at the Console, which is where the full Git message is kept. The dialog offers **Open Console**, **Copy details**, and **Close**. + ## Troubleshooting **The panel reports that Git is not usable.** Git is not installed, or it is not on the `PATH` the Editor was started with. Install Git and restart the Editor. @@ -63,6 +83,8 @@ The panel updates the file lists automatically, at most once per second. If you **The icons are missing.** The icons are vector artwork that the Editor rasterizes when the panel first opens. If the Editor was started without GPU support, or the textures could not be uploaded, the panel falls back to text-only controls and the status codes still work. +**An operation fails and the panel looks unchanged.** The panel writes the reason to the Editor Console. Open the Console window to read it — the full Git output is kept there, so it stays available after the message box closes. + ## Licences The plugin ships its own licence and the notices for the icon artwork with the plugin itself. Open the **License** tab of this plugin to read them. @@ -77,4 +99,4 @@ https://github.com/Wokrlie/InxGitIntegration/blob/main/LICENSE ## Upcoming features -Branch display and switching, discard-changes for unstaged files, Push/Pull controls, diff preview, and asynchronous `git status` execution are planned for future versions. +Discard-changes for unstaged files, Push/Pull controls, and diff preview are planned for future versions. diff --git a/package/plugin_pages/usage.zh-CN.md b/package/plugin_pages/usage.zh-CN.md index 84c5e3f..78fe2ad 100644 --- a/package/plugin_pages/usage.zh-CN.md +++ b/package/plugin_pages/usage.zh-CN.md @@ -14,9 +14,10 @@ Git 面板让你直接在 Infernux 编辑器里完成暂存、取消暂存和提 ## 面板结构 -正常界面从上到下分四部分: +正常界面从上到下分五部分: - **源代码管理** —— 标题栏。右侧的刷新图标会立即执行一次 `git status`,跳过刷新间隔。 +- **分支** —— 当前所在分支、分支列表、作用于所选分支的操作、它的提交日志,以及新建分支的那一行。 - **已暂存的更改** —— 下次提交会包含的文件。 - **更改** —— 已修改或删除、但还没暂存的文件,以及未跟踪的文件。 - **提交区** —— 消息输入框和**提交**按钮。 @@ -51,6 +52,25 @@ Git 面板让你直接在 Infernux 编辑器里完成暂存、取消暂存和提 面板会自动更新文件列表,最多每秒一次。如果你想立刻看到当前状态——比如刚在终端里执行过 Git 命令——点击标题栏右侧的刷新图标。 +## 管理分支 + +面板的**分支**分组里是所有和分支有关的东西。首次打开面板时该分组默认展开,可以像文件列表一样折叠收起。 + +- 第一行是项目当前所在的分支,以及它的上游和与上游的偏差(`↑2 ↓1`)。 +- 下面的列表先列本地分支,再列远端分支。当前分支前面有一个圆点标记,跟踪了别的分支的条目会在右侧显示它的上游。 +- 在过滤框里输入内容可以缩小列表范围。过滤只是改变显示内容,不会执行任何命令。 +- 点击某个分支即可选中它。选中的分支前面有一个箭头标记,下方的操作都作用于它。 +- **切换**会切到选中的分支。切换在后台执行,即使在大仓库里面板也不会卡住。 +- **重命名**会展开一个输入框让你填新名字。名字在使用前会先校验,分支名可以包含 `/`,例如 `feature/new-panel`。 +- **删除**会删掉选中的分支。Git 会拒绝删除还有未合并提交的分支;**强制删除**则照样删掉,那些提交仍留在 git 的 reflog 里。 +- 在底部的输入框里填写名字并点击**创建**,就会从当前提交新建一个分支并切换过去。 + +### 分支日志 + +操作区下面是**分支日志**,按时间倒序列出所选分支的提交,每条显示提交的短哈希和提交信息。日志保留最近 50 个提交,在后台获取,历史再长的分支也不会拖慢面板。每次提交之后日志都会重新获取,所以刚做出的提交立刻就能看到。 + +如果切换失败——通常是因为工作区有改动,而目标分支会覆盖它们——弹窗会用一句话说明出了什么问题,并指向 Console,完整的 Git 信息都留在那里。弹窗提供**打开 Console**、**复制详情**和**关闭**三个按钮。 + ## 故障排查 **面板提示当前环境无法使用 Git。** 系统没有安装 Git,或者 Editor 启动时的 `PATH` 里找不到它。安装 Git 后重启 Editor。 @@ -68,6 +88,8 @@ git config --global user.email "you@example.com" **图标没有显示。** 图标是矢量素材,由编辑器在面板首次打开时完成光栅化。如果 Editor 启动时没有 GPU 支持,或者纹理上传失败,面板会退回到纯文字控件,状态码仍然正常工作。 +**操作失败,但面板看起来毫无变化。** 面板会把失败原因写进 Editor 的 Console。打开 Console 窗口就能看到——完整的 Git 输出都留在那里,关闭提示之后依然可以回看。 + ## 许可证 插件自身的许可证和图标素材的第三方声明都随插件一起分发。在本插件的**许可证**标签页里可以读到它们。 @@ -82,4 +104,4 @@ https://github.com/Wokrlie/InxGitIntegration/blob/main/LICENSE ## 后续计划 -后续版本将支持分支显示与切换、未暂存文件的丢弃改动、Push / Pull 控制、diff 预览,以及异步执行 `git status`。 +后续版本将支持丢弃未暂存文件的改动、Push / Pull 控制和 diff 预览。 diff --git a/tests/test_engine_api_usage.py b/tests/test_engine_api_usage.py new file mode 100644 index 0000000..86e4e0e --- /dev/null +++ b/tests/test_engine_api_usage.py @@ -0,0 +1,142 @@ +"""The plugin must only call Engine APIs that actually exist. + +``Debug.error`` looks perfectly reasonable, but the Engine exposes +``Debug.log_error`` and nothing else with that name. The call therefore +raised ``AttributeError`` at runtime, so every Git failure in the panel was +reported as an unrelated Python traceback and the real message never +reached the Console. + +A review will not catch that reliably, so this test scans the plugin +sources and fails on any method the Engine does not provide. + +The allowlists below were transcribed from the Engine sources: + +* ``python/infernux/debug.py`` — the ``Debug`` class. +* ``cpp/infernux/function/resources/.../InxGUIContext.h`` and + ``python/infernux/engine/ui/BindingGUI.cpp`` — the ImGui context. + +They were checked against the upstream ``master`` branch on 2026-11-06. +``input_uint`` and ``push_id_str`` were dropped from the allowlist in that +pass: the Engine no longer declares them, so keeping them would let a +call to a method that does not exist pass this test and then fail at +runtime with the very ``AttributeError`` this test exists to prevent. +""" + +from pathlib import Path +import re +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +EDITOR = ROOT / "package" / "editor" + +#: Methods of ``infernux.debug.Debug``. +DEBUG_METHODS = frozenset({ + "log", + "log_warning", + "log_error", + "log_exception", + "log_suppressed", + "log_assert", + "clear_console", + "clear_source_entries", + "log_internal", + "log_debug", + "report_script_error", + "report_internal_error", + "report_recovered", +}) + +#: Methods of ``infernux.lib.InxGUIContext``. +CONTEXT_METHODS = frozenset({ + # text and simple widgets + "label", "field_label", "text_wrapped", "button", "radio_button", + "checkbox", "checkbox_inspector", "checkbox_flags", "separator", + "spacing", "dummy", "new_line", "same_line", "align_text_to_frame_padding", + "progress_bar", "text_input", "text_area", "input_text_with_hint", + "input_int", "input_float", "int_slider", "float_slider", + "drag_float", "drag_int", "color_edit", "color_picker", "vector2_control", + "vector3_control", "vector4_control", "input_text_multiline", + # lists, combos and popups + "selectable", "selectable_row", "selectable_list_clipped", "combo", + "searchable_combo", "list_box", "tree_node", "tree_node_ex", "tree_pop", + "open_popup", "begin_popup", "begin_popup_modal", "begin_popup_context_item", + "begin_popup_context_window", "end_popup", "close_current_popup", + "begin_tooltip", "end_tooltip", "set_tooltip", + # containers + "begin_group", "end_group", "begin_framed_group", "end_framed_group", + "begin_child", "end_child", "begin_window", "end_window", "begin_tab_bar", + "end_tab_bar", "begin_tab_item", "end_tab_item", "begin_main_menu_bar", + "end_main_menu_bar", "begin_menu", "end_menu", "menu_item", + "collapsing_header", "render_compact_section_header", "begin_table", + "end_table", "table_setup_column", "table_headers_row", "table_next_row", + "table_set_column_index", "table_next_column", "invisible_button", + # images and drawing + "image", "image_button", "draw_rect", "draw_filled_rect", + "draw_filled_rect_rotated", "draw_line", "draw_circle", + "draw_filled_circle", "draw_image_rect", "draw_text", "draw_text_aligned", + # style and state + "push_style_color", "pop_style_color", "push_style_var_float", + "push_style_var_vec2", "pop_style_var", "begin_disabled", "end_disabled", + "push_id", "pop_id", "set_next_item_width", + "set_next_item_open", "set_next_item_allow_overlap", "set_next_window_size", + "set_next_window_pos", "set_next_window_focus", "set_window_focus", + "set_window_font_scale", "set_keyboard_focus_here", "set_cursor_pos_x", + "set_cursor_pos_y", "set_cursor_screen_pos", "set_scroll_x", "set_scroll_y", + "set_scroll_here_y", "set_clipboard_text", "get_clipboard_text", + "set_mouse_cursor", + # queries + "is_item_clicked", "is_item_active", "is_item_edited", "is_any_item_active", + "is_item_hovered", "is_item_focused", "is_item_deactivated", + "is_item_deactivated_after_edit", "is_window_focused", "is_window_hovered", + "is_mouse_button_down", "is_mouse_button_clicked", "is_mouse_double_clicked", + "is_mouse_dragging", "is_key_down", "is_key_pressed", "is_key_released", + "is_current_window_content_presented", "is_virtualized_region_visible", + "want_text_input", "get_mouse_pos_x", "get_mouse_pos_y", + "get_mouse_wheel_delta", "get_mouse_drag_delta_x", "get_mouse_drag_delta_y", + "get_window_pos_x", "get_window_pos_y", "get_window_width", + "get_item_rect_min_x", "get_item_rect_min_y", "get_item_rect_max_x", + "get_item_rect_max_y", "get_cursor_pos_x", "get_cursor_pos_y", + "get_content_region_avail_width", "get_content_region_avail_height", + "get_scroll_y", "get_scroll_max_y", "get_dpi_scale", "calc_text_width", + "get_main_viewport_bounds", "get_display_bounds", "get_global_mouse_pos_x", + "get_global_mouse_pos_y", +}) + +CALL = re.compile(r"\b(Debug|ctx)\.([a-z_][a-z0-9_]*)\s*\(") + + +def editor_sources(): + for path in sorted(EDITOR.rglob("*.py")): + yield path, path.read_text(encoding="utf-8") + + +class EngineApiUsageTests(unittest.TestCase): + def test_allowlists_are_populated(self): + self.assertGreater(len(DEBUG_METHODS), 5) + self.assertGreater(len(CONTEXT_METHODS), 20) + + def test_plugin_only_calls_engine_apis_that_exist(self): + unknown = [] + for path, source in editor_sources(): + for prefix, name in CALL.findall(source): + allowed = DEBUG_METHODS if prefix == "Debug" else CONTEXT_METHODS + if name not in allowed: + unknown.append(f"{path.relative_to(ROOT)}: {prefix}.{name}") + self.assertEqual( + unknown, [], + "These Engine methods do not exist. The call will raise " + "AttributeError at runtime: " + ", ".join(sorted(set(unknown))), + ) + + def test_debug_errors_use_the_method_that_exists(self): + """The regression that started this: ``Debug.error`` is not an API.""" + for path, source in editor_sources(): + self.assertNotIn( + "Debug.error(", source, + f"{path.relative_to(ROOT)} still calls the non-existent Debug.error", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_git_repository.py b/tests/test_git_repository.py new file mode 100644 index 0000000..7da30e4 --- /dev/null +++ b/tests/test_git_repository.py @@ -0,0 +1,416 @@ +"""The git commands against real repositories. + +These tests run the real ``git`` executable in a throwaway repository, so +they cover the command line as Git actually answers it rather than a +recorded sample. +""" + +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import time +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "package" / "editor" / "wokrlie")) + +from git_integration.git import ( # noqa: E402 + GitCommand, + GitRunner, + checkout, + commit, + create_branch, + delete_branch, + init_repository, + list_branches, + parse_status, + read_log, + read_repository_state, + read_status, + rename_branch, + stage_all, + stage_file, + unstage_file, + validate_branch_name, +) + + +GIT = shutil.which("git") + + +@unittest.skipIf(GIT is None, "git is required for this test") +class GitRepositoryTests(unittest.TestCase): + def setUp(self): + self.workspace = tempfile.TemporaryDirectory() + self.addCleanup(self.workspace.cleanup) + self.root = Path(self.workspace.name) + self.repo = self.root / "repo" + self.repo.mkdir() + self.runner = GitRunner(str(self.repo)) + self.git("init") + self.git("config", "user.email", "panel@example.com") + self.git("config", "user.name", "Panel Test") + self.git("symbolic-ref", "HEAD", "refs/heads/main") + + def git(self, *args, cwd=None): + return subprocess.run( + ["git", *args], + cwd=str(cwd or self.repo), + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + check=True, + ) + + def commit(self, message="commit"): + (self.repo / "tracked.txt").write_text(message, encoding="utf-8") + self.git("add", "-A") + self.git("commit", "-m", message) + + def snapshot(self): + result = read_status(self.runner) + self.assertTrue(result.ok, result.stderr) + return parse_status(result.stdout) + + # -- status ------------------------------------------------------- # + def test_unborn_repository_reports_the_branch_name(self): + snapshot = self.snapshot() + self.assertEqual(snapshot.branch, "main") + self.assertFalse(snapshot.detached) + self.assertEqual(snapshot.unstaged, {}) + + def test_the_state_pass_carries_the_branch_list(self): + """The branch section draws from the same background pass.""" + self.commit() + self.git("branch", "feature/nested") + state = read_repository_state(self.runner) + self.assertTrue(state.inside) + self.assertIsNotNone(state.snapshot) + names = [branch.name for branch in state.branches] + self.assertIn("main", names) + self.assertIn("feature/nested", names) + + def test_a_folder_outside_a_repository_is_reported(self): + outside = self.root / "not-a-repo" + outside.mkdir() + state = read_repository_state(GitRunner(str(outside))) + self.assertFalse(state.inside) + self.assertIsNone(state.snapshot) + self.assertEqual(state.branches, []) + self.assertIsNotNone(state.error) + + def test_modified_untracked_and_staged_files(self): + self.commit() + (self.repo / "tracked.txt").write_text("changed", encoding="utf-8") + (self.repo / "fresh.txt").write_text("new", encoding="utf-8") + + snapshot = self.snapshot() + self.assertEqual(snapshot.unstaged, {"tracked.txt": "M"}) + self.assertEqual(snapshot.untracked, ["fresh.txt"]) + + self.git("add", "tracked.txt") + snapshot = self.snapshot() + self.assertEqual(snapshot.staged, {"tracked.txt": "M"}) + + def test_rename_keeps_the_new_path(self): + self.commit() + self.git("mv", "tracked.txt", "renamed.txt") + snapshot = self.snapshot() + self.assertIn("renamed.txt", snapshot.staged) + self.assertNotIn("tracked.txt", snapshot.staged) + + def test_non_ascii_path_is_reported_verbatim(self): + (self.repo / "名字 file.txt").write_text("u", encoding="utf-8") + self.git("add", "-A") + self.git("commit", "-m", "unicode") + (self.repo / "名字 file.txt").write_text("changed", encoding="utf-8") + + snapshot = self.snapshot() + self.assertEqual(list(snapshot.unstaged), ["名字 file.txt"]) + + def test_detached_head_is_reported(self): + self.commit() + self.git("checkout", "HEAD~0", "--detach") + snapshot = self.snapshot() + self.assertTrue(snapshot.detached) + self.assertTrue(snapshot.oid) + self.assertEqual(len(snapshot.oid), 40) + + # -- branches ----------------------------------------------------- # + def test_local_branches_are_listed_with_the_current_one_marked(self): + self.commit() + self.git("branch", "feature/nested") + self.git("branch", "other") + + branches = list_branches(self.runner) + names = [branch.name for branch in branches] + self.assertIn("main", names) + self.assertIn("feature/nested", names) + self.assertIn("other", names) + current = [branch for branch in branches if branch.current] + self.assertEqual([branch.name for branch in current], ["main"]) + + def test_remote_branches_are_listed_without_the_symbolic_head(self): + remote = self.root / "remote.git" + self.git("init", "--bare", "-b", "main", str(remote), cwd=self.root) + self.commit() + self.git("remote", "add", "origin", str(remote)) + self.git("push", "-u", "origin", "main") + self.git("fetch", "origin") + + branches = list_branches(self.runner) + remote_names = [branch.name for branch in branches if branch.remote] + self.assertIn("origin/main", remote_names) + self.assertNotIn("origin", remote_names) + + def test_upstream_is_reported_for_the_current_branch(self): + remote = self.root / "remote.git" + self.git("init", "--bare", "-b", "main", str(remote), cwd=self.root) + self.commit() + self.git("remote", "add", "origin", str(remote)) + self.git("push", "-u", "origin", "main") + + snapshot = self.snapshot() + self.assertEqual(snapshot.upstream, "origin/main") + self.assertEqual(snapshot.ahead, 0) + self.assertEqual(snapshot.behind, 0) + + # -- names -------------------------------------------------------- # + def test_valid_branch_names_are_accepted(self): + for name in ("main", "feature/nested", "功能/测试", "release-1.2"): + with self.subTest(name=name): + self.assertEqual(validate_branch_name(self.runner, name), name) + + def test_dangerous_branch_names_are_rejected(self): + for name in ("", " ", "-foo", "--foo", "bad name", "HEAD", "@{-1}"): + with self.subTest(name=name): + self.assertEqual(validate_branch_name(self.runner, name), "") + + # -- actions ------------------------------------------------------ # + def test_create_branch_starts_from_the_current_head(self): + self.commit() + result = create_branch(self.runner, "feature/from-head") + self.assertTrue(result.ok, result.stderr) + self.assertEqual(self.snapshot().branch, "feature/from-head") + + def test_checkout_returns_to_the_previous_branch(self): + self.commit() + self.git("branch", "side") + result = checkout(self.runner, "side") + self.assertTrue(result.ok, result.stderr) + self.assertEqual(self.snapshot().branch, "side") + result = checkout(self.runner, "main") + self.assertTrue(result.ok, result.stderr) + self.assertEqual(self.snapshot().branch, "main") + + def test_checkout_reports_the_files_that_block_it(self): + self.commit() + self.git("checkout", "-b", "topic") + (self.repo / "tracked.txt").write_text("topic", encoding="utf-8") + self.git("commit", "-am", "topic change") + self.git("checkout", "main") + (self.repo / "tracked.txt").write_text("main", encoding="utf-8") + + result = checkout(self.runner, "topic") + self.assertFalse(result.ok) + self.assertIn("would be overwritten", result.summary) + + def test_a_failure_carries_the_command_line_and_the_exit_code(self): + """The Console entry quotes both, so a failure can be run by hand.""" + result = checkout(self.runner, "no-such-branch") + self.assertFalse(result.ok) + self.assertEqual(result.command, "git checkout no-such-branch") + self.assertNotEqual(result.returncode, 0) + self.assertTrue(result.stderr.strip()) + + def test_unstage_works_without_a_commit(self): + """``git reset HEAD -- `` is enough in an empty repository.""" + (self.repo / "fresh.txt").write_text("new", encoding="utf-8") + self.git("add", "-A") + self.assertEqual(self.snapshot().staged, {"fresh.txt": "A"}) + + result = self.runner.run("reset", "HEAD", "--", "fresh.txt") + self.assertTrue(result.ok, result.stderr) + snapshot = self.snapshot() + self.assertEqual(snapshot.staged, {}) + self.assertEqual(snapshot.untracked, ["fresh.txt"]) + + def test_unstage_keeps_the_file_tracked_when_a_commit_exists(self): + self.commit() + (self.repo / "tracked.txt").write_text("changed", encoding="utf-8") + self.git("add", "-A") + + result = self.runner.run("reset", "HEAD", "--", "tracked.txt") + self.assertTrue(result.ok, result.stderr) + snapshot = self.snapshot() + self.assertEqual(snapshot.staged, {}) + self.assertEqual(snapshot.unstaged, {"tracked.txt": "M"}) + + # -- branch maintenance ------------------------------------------- # + def test_renaming_a_branch_keeps_the_commits(self): + self.commit() + self.git("branch", "old-name") + result = rename_branch(self.runner, "old-name", "new/name") + self.assertTrue(result.ok, result.stderr) + names = [branch.name for branch in list_branches(self.runner)] + self.assertIn("new/name", names) + self.assertNotIn("old-name", names) + + def test_renaming_onto_an_existing_name_is_refused(self): + self.commit() + self.git("branch", "taken") + result = rename_branch(self.runner, "main", "taken") + self.assertFalse(result.ok) + self.assertIn("already exists", result.stderr) + + def test_renaming_to_an_invalid_name_never_reaches_git(self): + self.commit() + result = rename_branch(self.runner, "main", "-danger") + self.assertFalse(result.ok) + self.assertIn("not a valid branch name", result.stderr) + + def test_creating_a_branch_with_an_invalid_name_is_refused(self): + self.commit() + result = create_branch(self.runner, "-danger") + self.assertFalse(result.ok) + self.assertIn("not a valid branch name", result.stderr) + + def test_deleting_a_merged_branch_works(self): + self.commit() + self.git("branch", "gone") + result = delete_branch(self.runner, "gone") + self.assertTrue(result.ok, result.stderr) + names = [branch.name for branch in list_branches(self.runner)] + self.assertNotIn("gone", names) + + def test_deleting_an_unmerged_branch_needs_the_force(self): + self.commit() + self.git("checkout", "-b", "work") + (self.repo / "tracked.txt").write_text("work", encoding="utf-8") + self.git("commit", "-am", "work") + self.git("checkout", "main") + + result = delete_branch(self.runner, "work") + self.assertFalse(result.ok) + self.assertIn("not fully merged", result.stderr) + + forced = delete_branch(self.runner, "work", force=True) + self.assertTrue(forced.ok, forced.stderr) + names = [branch.name for branch in list_branches(self.runner)] + self.assertNotIn("work", names) + + def test_the_branch_the_project_is_on_cannot_be_deleted(self): + self.commit() + result = delete_branch(self.runner, "main", force=True) + self.assertFalse(result.ok) + self.assertIn("delete branch", result.stderr.lower()) + + def test_the_operations_use_the_same_worker_as_the_panel(self): + """Every mutating operation returns a result the panel can report.""" + self.commit() + (self.repo / "tracked.txt").write_text("changed", encoding="utf-8") + for result in ( + stage_file(self.runner, "tracked.txt"), + unstage_file(self.runner, "tracked.txt"), + stage_all(self.runner), + commit(self.runner, "a message"), + checkout(self.runner, "main"), + ): + with self.subTest(command=result.command): + self.assertTrue(result.ok, result.stderr) + self.assertTrue(result.command.startswith("git ")) + + # -- log ---------------------------------------------------------- # + def test_the_log_lists_the_commits_newest_first(self): + self.commit("first commit") + self.commit("second commit") + + entries = read_log(self.runner, "main") + self.assertEqual(len(entries), 2) + self.assertEqual( + [entry.subject for entry in entries], + ["second commit", "first commit"], + ) + + def test_the_log_keeps_a_subject_that_contains_spaces(self): + self.commit("feat: add the panel 面板") + + entries = read_log(self.runner, "main") + self.assertEqual(len(entries), 1) + self.assertEqual(entries[0].subject, "feat: add the panel 面板") + + def test_the_log_reports_the_short_hash_of_each_commit(self): + self.commit() + head = self.git("rev-parse", "HEAD").stdout.strip() + + entries = read_log(self.runner, "main") + self.assertTrue(head.startswith(entries[0].sha)) + self.assertLessEqual(len(entries[0].sha), 7) + + def test_the_log_of_a_branch_without_commits_is_empty(self): + """A branch that was never committed to has no log to show.""" + self.assertEqual(read_log(self.runner, "main"), []) + + self.commit() + self.git("checkout", "--orphan", "empty-branch") + self.assertEqual(read_log(self.runner, "empty-branch"), []) + + def test_the_log_of_a_branch_that_does_not_exist_is_empty(self): + self.commit() + self.assertEqual(read_log(self.runner, "no-such-branch"), []) + + def test_the_log_honours_the_limit(self): + for index in range(5): + self.commit(f"commit {index}") + + entries = read_log(self.runner, "main", limit=2) + self.assertEqual(len(entries), 2) + self.assertEqual(entries[0].subject, "commit 4") + + def test_the_log_follows_the_branch_it_was_asked_for(self): + self.commit("on main") + self.git("checkout", "-b", "side") + self.commit("on side") + + main_entries = read_log(self.runner, "main") + side_entries = read_log(self.runner, "side") + self.assertEqual([entry.subject for entry in main_entries], ["on main"]) + self.assertEqual( + [entry.subject for entry in side_entries], ["on side", "on main"] + ) + + # -- async -------------------------------------------------------- # + def wait_for(self, command): + """Poll a worker command until it reports a result.""" + for _ in range(500): + result = command.poll() + if result is not None: + return result + time.sleep(0.01) + self.fail("the worker thread never finished") + + def test_command_returns_none_until_it_finishes(self): + command = GitCommand.command(self.runner, ("status", "--porcelain=v2", "-z", "--branch")) + self.assertIsNone(command.poll()) + command.start() + result = self.wait_for(command) + self.assertTrue(result.ok, result.stderr) + + def test_command_keeps_the_utf8_paths(self): + (self.repo / "名字 file.txt").write_text("u", encoding="utf-8") + self.git("add", "-A") + self.git("commit", "-m", "unicode") + (self.repo / "名字 file.txt").write_text("changed", encoding="utf-8") + + command = GitCommand.command(self.runner, ("status", "--porcelain=v2", "-z", "--branch")) + command.start() + result = self.wait_for(command) + self.assertIn("名字 file.txt", result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_git_status_parsing.py b/tests/test_git_status_parsing.py new file mode 100644 index 0000000..ec4eaba --- /dev/null +++ b/tests/test_git_status_parsing.py @@ -0,0 +1,149 @@ +"""The porcelain v2 status parser. + +The samples below are the raw bytes of real ``git status --porcelain=v2 -z +--branch`` runs, captured on git 2.55 and only edited for readability. +""" + +from pathlib import Path +import sys +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "package" / "editor" / "wokrlie")) + +from git_integration.git import parse_status # noqa: E402 + + +class StatusParsingTests(unittest.TestCase): + def test_unborn_branch_reports_its_name(self): + payload = "# branch.oid (initial)\0# branch.head main\0" + snapshot = parse_status(payload) + self.assertEqual(snapshot.branch, "main") + self.assertFalse(snapshot.detached) + self.assertEqual(snapshot.oid, "") + self.assertEqual(snapshot.staged, {}) + self.assertEqual(snapshot.unstaged, {}) + self.assertEqual(snapshot.untracked, []) + + def test_modified_and_untracked_entries(self): + payload = ( + "# branch.oid b4ae9d58ae408c1512b316fee7c5c24e05031d24\0" + "# branch.head main\0" + "1 .M N... 100644 100644 100644 " + "c1b0730e0133447badcfd47fd144e254807b06e1 " + "c1b0730e0133447badcfd47fd144e254807b06e1 a.txt\0" + "? new.txt\0" + ) + snapshot = parse_status(payload) + self.assertEqual(snapshot.branch, "main") + self.assertEqual(snapshot.unstaged, {"a.txt": "M"}) + self.assertEqual(snapshot.staged, {}) + self.assertEqual(snapshot.untracked, ["new.txt"]) + + def test_dual_state_lands_in_both_lists(self): + payload = ( + "# branch.oid b4ae9d58ae408c1512b316fee7c5c24e05031d24\0" + "# branch.head main\0" + "1 AM N... 100644 100644 100644 " + "c1b0730e0133447badcfd47fd144e254807b06e1 " + "c1b0730e0133447badcfd47fd144e254807b06e1 both.txt\0" + ) + snapshot = parse_status(payload) + self.assertEqual(snapshot.staged, {"both.txt": "A"}) + self.assertEqual(snapshot.unstaged, {"both.txt": "M"}) + + def test_rename_keeps_the_new_path_and_skips_the_original(self): + payload = ( + "# branch.oid b4ae9d58ae408c1512b316fee7c5c24e05031d24\0" + "# branch.head main\0" + "2 RM N... 100644 100644 100644 " + "c1b0730e0133447badcfd47fd144e254807b06e1 " + "c1b0730e0133447badcfd47fd144e254807b06e1 R100 b.txt\0" + "a.txt\0" + "? new.txt\0" + ) + snapshot = parse_status(payload) + self.assertEqual(snapshot.staged, {"b.txt": "R"}) + self.assertEqual(snapshot.unstaged, {"b.txt": "M"}) + self.assertNotIn("a.txt", snapshot.staged) + self.assertNotIn("a.txt", snapshot.unstaged) + self.assertEqual(snapshot.untracked, ["new.txt"]) + + def test_non_ascii_path_stays_literal(self): + """The v1 format escaped this into octal; v2 with -z does not.""" + payload = ( + "# branch.oid 0a8c200fcc1991e1fed788f630b87005cd1c1684\0" + "# branch.head main\0" + "1 .M N... 100644 100644 100644 " + "f3c6c3c68af484bd95bc7b7a38276c6c014d6aa3 " + "f3c6c3c68af484bd95bc7b7a38276c6c014d6aa3 名字 file.txt\0" + ) + snapshot = parse_status(payload) + self.assertEqual(list(snapshot.unstaged), ["名字 file.txt"]) + self.assertNotIn("\\345", list(snapshot.unstaged)[0]) + + def test_detached_head_is_reported(self): + payload = ( + "# branch.oid 2876a2c1f6e9bb32f3e7538858d5ecf92d78998b\0" + "# branch.head (detached)\0" + ) + snapshot = parse_status(payload) + self.assertTrue(snapshot.detached) + self.assertEqual(snapshot.branch, "") + self.assertEqual(snapshot.oid, "2876a2c1f6e9bb32f3e7538858d5ecf92d78998b") + + def test_the_commit_hash_is_kept_for_a_detached_head(self): + """The header names the commit, so the tooltip can show a short sha.""" + payload = ( + "# branch.oid 2876a2c1f6e9bb32f3e7538858d5ecf92d78998b\0" + "# branch.head (detached)\0" + ) + snapshot = parse_status(payload) + self.assertEqual(snapshot.oid[:7], "2876a2c") + + def test_upstream_and_ahead_behind(self): + payload = ( + "# branch.oid 6e3dae717eaed0fd1056eef56a76715406464b8b\0" + "# branch.head main\0" + "# branch.upstream origin/main\0" + "# branch.ab +3 -2\0" + ) + snapshot = parse_status(payload) + self.assertEqual(snapshot.upstream, "origin/main") + self.assertEqual(snapshot.ahead, 3) + self.assertEqual(snapshot.behind, 2) + + def test_conflict_entry_is_reported_in_both_lists(self): + payload = ( + "# branch.oid b4ae9d58ae408c1512b316fee7c5c24e05031d24\0" + "# branch.head main\0" + "u UU N... 100644 100644 100644 100644 " + "c1b0730e0133447badcfd47fd144e254807b06e1 " + "c1b0730e0133447badcfd47fd144e254807b06e1 " + "c1b0730e0133447badcfd47fd144e254807b06e1 conflict.txt\0" + ) + snapshot = parse_status(payload) + self.assertEqual(snapshot.staged, {"conflict.txt": "U"}) + self.assertEqual(snapshot.unstaged, {"conflict.txt": "U"}) + + def test_ignored_entries_are_skipped(self): + payload = ( + "# branch.oid b4ae9d58ae408c1512b316fee7c5c24e05031d24\0" + "# branch.head main\0" + "! ignored.txt\0" + ) + snapshot = parse_status(payload) + self.assertEqual(snapshot.staged, {}) + self.assertEqual(snapshot.unstaged, {}) + self.assertEqual(snapshot.untracked, []) + + def test_empty_payload_is_an_empty_snapshot(self): + snapshot = parse_status("") + self.assertEqual(snapshot.branch, "") + self.assertFalse(snapshot.detached) + self.assertEqual(snapshot.change_count, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_icon_assets.py b/tests/test_icon_assets.py index 5739ed1..f0ef39d 100644 --- a/tests/test_icon_assets.py +++ b/tests/test_icon_assets.py @@ -82,10 +82,29 @@ def test_every_status_icon_exists(self): self.assertIn(icon, self.paths) def test_action_icons_exist(self): - for icon in ("stage", "unstage", "stage-all", "refresh"): + for icon in ("stage", "unstage", "stage-all", "refresh", "git-branch", "chevron-down"): with self.subTest(icon=icon): self.assertIn(icon, self.paths) + def test_new_icons_match_the_upstream_lucide_geometry(self): + """The licence notice covers the upstream artwork, so it has to match. + + These two were compared element by element against the Lucide 0.544.0 + sources. ``chevron-down`` is geometrically identical to the Feather + icon of the same name, which is why the notices list it. + """ + upstream = { + "git-branch": ( + '' + '' + '' + ), + "chevron-down": '', + } + for name, body in upstream.items(): + with self.subTest(icon=name): + self.assertEqual(self.paths.get(name), body) + def test_colour_conversion_produces_valid_hex(self): to_hex = self.module["_to_hex"] self.assertEqual(to_hex((0.0, 0.0, 0.0, 1.0)), "#000000") diff --git a/tests/test_panel_action_contracts.py b/tests/test_panel_action_contracts.py new file mode 100644 index 0000000..70fdd94 --- /dev/null +++ b/tests/test_panel_action_contracts.py @@ -0,0 +1,103 @@ +"""The shape of the panel's background actions. + +Every git command runs on a worker thread, and the panel hands that +thread a job: a callable that returns the command result. The job is +built on the render thread, but it must not run a git command there — +a subprocess spawn on the render thread is a visible hitch in the +Editor. + +Two mistakes are easy to make and invisible in a review: + +* passing the argument list of a git command where a job belongs, or + the other way round — the first version of the unstage action did + exactly that and raised ``TypeError: 'function' object is not + subscriptable`` on the first click; +* running a git command on the render thread, which stalls the frame. + +Both are checked here instead of by a reviewer. +""" + +from pathlib import Path +import ast +import unittest + + +ROOT = Path(__file__).resolve().parents[1] +MODULE = ROOT / "package" / "editor" / "wokrlie" / "git_integration" +PANEL = MODULE / "panel.py" +GIT = MODULE / "git.py" + + +def calls_named(tree: ast.AST, name: str): + """Every call to a function or method called *name*.""" + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + if isinstance(func, ast.Attribute) and func.attr == name: + yield node + elif isinstance(func, ast.Name) and func.id == name: + yield node + + +class ActionContractTests(unittest.TestCase): + def test_every_action_starts_with_a_job(self): + tree = ast.parse(PANEL.read_text(encoding="utf-8")) + calls = list(calls_named(tree, "_start_action")) + self.assertGreater(len(calls), 0, "no _start_action call was found") + for call in calls: + with self.subTest(line=call.lineno): + self.assertTrue( + call.args, "_start_action needs the job to run" + ) + self.assertIsInstance( + call.args[0], + ast.Lambda, + "the first argument of _start_action has to be a job, " + "not a list of git arguments", + ) + + def test_the_panel_never_runs_a_git_command_itself(self): + """A git command on the render thread stalls the frame.""" + tree = ast.parse(PANEL.read_text(encoding="utf-8")) + for call in calls_named(tree, "run"): + with self.subTest(line=call.lineno): + self.fail( + "the panel must not call .run() itself: every git " + "command belongs in git.py and runs on a worker thread" + ) + + def test_the_panel_does_not_import_subprocess(self): + source = PANEL.read_text(encoding="utf-8") + tree = ast.parse(source) + for node in ast.walk(tree): + if not isinstance(node, ast.Import): + continue + for alias in node.names: + with self.subTest(module=alias.name): + self.assertNotEqual(alias.name, "subprocess") + with self.subTest(module=node.names[0].name): + self.assertNotEqual(node.names[0].name, "subprocess") + + def test_the_command_factory_takes_a_tuple(self): + """The annotation is the contract the factory relies on.""" + tree = ast.parse(GIT.read_text(encoding="utf-8")) + found = False + for node in ast.walk(tree): + if not isinstance(node, ast.FunctionDef): + continue + if node.name != "command": + continue + found = True + parameters = {arg.arg: arg for arg in node.args.args} + self.assertIn("args", parameters, "command() has no args parameter") + annotation = parameters["args"].annotation + self.assertIsNotNone(annotation, "args needs an annotation") + text = ast.dump(annotation) + self.assertIn("Tuple", text) + self.assertIn("str", text) + self.assertTrue(found, "GitCommand.command was not found") + + +if __name__ == "__main__": + unittest.main()