opencode-change-history 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,32 @@
1
+ # Changelog
2
+
3
+ English · [简体中文](./CHANGELOG.zh-CN.md)
4
+
5
+ All notable changes to this project will be documented in this file.
6
+
7
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
8
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
9
+
10
+ ## [Unreleased]
11
+
12
+ ## [0.1.0]
13
+
14
+ <!-- Add the actual release date (YYYY-MM-DD) when publishing. -->
15
+
16
+ Initial public release for OpenCode CLI v2.4.2.
17
+
18
+ ### Added
19
+
20
+ - **Changes** sidebar with cumulative statistics and a collapsible file tree.
21
+ - **Change history** dialog with per-file timelines, native unified diffs, and labeled partial previews.
22
+ - In-memory history from successful V2 and recognized migrated V1 tool records, with live updates, manual refresh, and undo-aware visibility.
23
+ - npm distribution as a TUI-only plugin with a native TSX entrypoint.
24
+
25
+ ### Known limitations
26
+
27
+ - History depends on the recorded metadata. Unrecorded edits, shell changes without structured results, and failed or unfinished tool calls are excluded.
28
+ - Some writes have no recorded diff. Creation estimates are shown separately from confirmed counts.
29
+ - OpenCode V1 cannot load the plugin, and the package provides no Desktop or web UI.
30
+
31
+ [Unreleased]: https://github.com/chenlongapps/opencode-change-history/compare/v0.1.0...HEAD
32
+ [0.1.0]: https://github.com/chenlongapps/opencode-change-history/releases/tag/v0.1.0
@@ -0,0 +1,31 @@
1
+ # 变更日志
2
+
3
+ [English](./CHANGELOG.md) · 简体中文
4
+
5
+ 本文件记录项目的所有重要变更。
6
+
7
+ 本文件的格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),项目遵循[语义化版本](https://semver.org/lang/zh-CN/spec/v2.0.0.html)规范。
8
+
9
+ ## [未发布]
10
+
11
+ ## [0.1.0]
12
+
13
+ <!-- 发布时填写实际发布日期(YYYY-MM-DD)。 -->
14
+
15
+ 首个公开版本,面向 OpenCode CLI v2.4.2。
16
+
17
+ ### 新增
18
+
19
+ - **Changes** 侧边栏展示累计统计和可折叠的文件树。
20
+ - **Change history** 弹窗展示逐文件时间线、原生统一格式 Diff,以及有明确标记的局部预览。
21
+ - 根据成功的 V2 工具记录和可识别的迁移后 V1 工具记录,在内存中生成变更历史。支持实时更新和手动刷新,并根据撤销状态调整历史记录的可见性。
22
+ - 通过 npm 分发纯 TUI 插件,提供原生 TSX 入口。
23
+
24
+ ### 已知限制
25
+
26
+ - 变更历史依赖已记录的元数据。未被记录的编辑、没有结构化结果的 Shell 变更,以及失败或未完成的工具调用均不计入。
27
+ - 部分写入操作没有记录 Diff。新建文件的估算行数与确认行数分开显示。
28
+ - OpenCode V1 无法加载此插件,本包也不提供桌面端或网页端界面。
29
+
30
+ [未发布]: https://github.com/chenlongapps/opencode-change-history/compare/v0.1.0...HEAD
31
+ [0.1.0]: https://github.com/chenlongapps/opencode-change-history/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OpenCode Change History contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # OpenCode Change History
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ English · [简体中文](./README.zh-CN.md)
4
+
5
+ View the file changes recorded for the current [OpenCode](https://opencode.ai/) terminal session, with per-file totals, edit history, and diffs.
6
+
7
+ **No Git. No Snapshots. No Extra Storage.** Change history is derived in memory from OpenCode's existing session records, even in projects without Git.
8
+
9
+ ## Features
10
+
11
+ - A **Changes** sidebar with cumulative line counts, an additions/deletions bar, and a collapsible file tree.
12
+ - A **Change history** dialog with a per-file timeline, native unified diffs, and clearly labeled partial previews.
13
+ - Updates as OpenCode records tool results, with manual refresh and support for staged undo, redo, and committed undo.
14
+ - Support for native OpenCode V2 tool results and recognized V1 tool records migrated into V2.
15
+
16
+ ## UI overview
17
+
18
+ | Where | What you see |
19
+ | --- | --- |
20
+ | Session sidebar → **Changes** | Session totals and the files with recorded changes. Files outside the session directory are grouped under **Other files**. |
21
+ | **Change history** in a wide terminal | Files on the left; the selected file's numbered edit history and diff on the right. Drag the divider to resize the file list. |
22
+ | **Change history** in a narrow terminal | One pane at a time. Open a file to see its history and diff, then use **‹ Files** to return. |
23
+
24
+ ## Install from npm
25
+
26
+ Use **OpenCode CLI v2.4.2**, the compatibility target for this release. Install the plugin with:
27
+
28
+ ```sh
29
+ opencode plugin add opencode-change-history@latest
30
+ ```
31
+
32
+ Or add the same entry to `~/.config/opencode/cli.json` (or `$XDG_CONFIG_HOME/opencode/cli.json`), preserving your other settings:
33
+
34
+ ```json
35
+ {
36
+ "plugins": ["opencode-change-history@latest"]
37
+ }
38
+ ```
39
+
40
+ OpenCode installs the package and loads its `./tui` TSX entry. This is a TUI-only plugin, so configure it in `cli.json`. A global npm installation, separate service, and build step are unnecessary. OpenCode watches `cli.json`; use `/reload` if you need to force a reload.
41
+
42
+ ## Usage
43
+
44
+ 1. Open or create a session and show the session sidebar to see **Changes**.
45
+ 2. Select **View details ›**, enter `/changes`, or choose **Session change history** in the command palette. The shortcut is `<leader>` then `h` (`Ctrl+X` then `h` with the default Leader). Clicking a file in the sidebar opens its latest recorded edit directly.
46
+ 3. Use `Tab` / `Shift+Tab` to change focus. In the file list, use the arrow keys to navigate, `Enter` to open a file, `v` to toggle the tree/list view, and `s` to change sorting. In the timeline, click a numbered edit or use `←` / `→` and `Home` / `End`. In the diff, use the arrow keys to pan. `Page Up` / `Page Down` scroll the file list when it has focus, and the diff otherwise. Press `r` to refresh or `Esc` to close the dialog.
47
+
48
+ ## Update
49
+
50
+ The installation example uses `@latest` so OpenCode can manage updates. If you pin a version in `cli.json`, update it by replacing it with a newer compatible version. See [OpenCode's plugin documentation](https://opencode.ai/docs/plugins#manage).
51
+
52
+ ## Disable or uninstall
53
+
54
+ - **Disable temporarily:** add `"-opencode-change-history"` after the installation entry in `cli.json`. Remove the disable entry to enable it again.
55
+ - **Uninstall:** remove the installation and any disable entries from `cli.json`, or run `opencode plugin remove opencode-change-history@latest` (substitute the exact specifier you installed if different) and remove any disable entry. OpenCode may retain its own package cache and UI preferences. Your session history stays in OpenCode.
56
+
57
+ ## How it works
58
+
59
+ The plugin pages through the current session's messages using the public OpenCode V2 client. It extracts file operations from successful tool results and aggregates them in memory. Tool-completion events trigger incremental updates. Switching sessions drops the previous session's in-memory history; reconnecting or refreshing reloads it from OpenCode.
60
+
61
+ The plugin doesn't use Git, snapshots, the working tree, or the OpenCode database to reconstruct changes. OpenCode manages the installation cache and saves the dialog's splitter width when you resize it. The plugin stores no separate change history.
62
+
63
+ ## Counting rules
64
+
65
+ - Totals measure work recorded over time. Adding 10 lines and later removing those same lines counts as **+10 / −10**.
66
+ - Successful `edit`, `patch`, `write`, migrated `apply_patch`, and tools such as Code Mode `execute` with explicit file-change metadata can contribute. Failed or unfinished calls and shell commands without structured file-change results do not count.
67
+ - Known line counts contribute to confirmed totals. `?` means counts are incomplete; a wholly unknown direction may be omitted. The bar uses known counts only.
68
+ - `~` marks a display total that includes estimated added lines from the submitted text of a confirmed `write` creation. Estimates stay out of confirmed totals. `Partial` marks records lacking a full diff or complete line counts. Previews synthesized from tool input are labeled and cannot confirm changes.
69
+ - Staged undo hides the affected history until redo. Committed undo removes the history whose messages OpenCode deleted. Forks show the history OpenCode copied; subagent changes appear in their own sessions.
70
+
71
+ ## Known limitations
72
+
73
+ - Edits made outside the session's recorded tools are invisible. Shell changes without metadata, and file changes a tool made before failing, cannot be reconstructed.
74
+ - `write` overwrites may record an operation without a diff. Code Mode limits how many changes it records and how large patches can be.
75
+ - Paths are normalized lexically. Unrecorded working directories, symlinks, and aliases across environments cannot be resolved retroactively. Moves with both paths recorded appear under the destination.
76
+
77
+ ## Compatibility
78
+
79
+ This release targets **OpenCode CLI v2.4.2** (OpenCode V2, OpenTUI 0.9.9, Solid 1.9.17). Other OpenCode versions and platforms are not covered by the release verification. OpenCode V1 is not supported as a host. This package has no Desktop or web UI.
80
+
81
+ ## Local development and testing
82
+
83
+ From the repository root, use Bun 1.4.2, Node.js/npm, and `tar`:
84
+
85
+ ```sh
86
+ bun install --frozen-lockfile
87
+ bun test
88
+ bun run check
89
+ npm pack --dry-run
90
+ archive=$(npm pack)
91
+ node scripts/check-package.mjs "$archive"
92
+ ```
93
+
94
+ To load the source for one launch, run this from the project you want to open. Substitute the absolute path to the plugin repository:
95
+
96
+ ```sh
97
+ OPENCODE_CLI_CONFIG_CONTENT='{"plugins":["/absolute/path/to/opencode-change-history"]}' opencode
98
+ ```
99
+
100
+ The parser in `src/core/` processes session messages and tool results without importing the SDK or the TUI runtime. `src/session-history.ts` connects it to the SDK, and `src/tui.tsx` registers the sidebar and dialog command. See the [OpenCode TUI plugin guide](https://opencode.ai/docs/build/plugins/cli) and the [changelog](./CHANGELOG.md).
101
+
102
+ ## License
103
+
104
+ [MIT](./LICENSE)
@@ -0,0 +1,104 @@
1
+ # OpenCode Change History
2
+
3
+ [English](./README.md) · 简体中文
4
+
5
+ 查看 [OpenCode](https://opencode.ai/) 当前终端会话中已记录的文件变更,包括逐文件统计、修改历史和 Diff。
6
+
7
+ **No Git. No Snapshots. No Extra Storage.** 变更历史根据 OpenCode 已有的会话记录在内存中生成,也适用于非 Git 项目。
8
+
9
+ ## 核心特性
10
+
11
+ - **Changes** 侧边栏展示累计行数、增删行比例和可折叠的文件树。
12
+ - **Change history** 弹窗展示逐文件时间线、原生统一格式 Diff,以及有明确标记的局部预览。
13
+ - 随 OpenCode 记录工具结果而更新,支持手动刷新,以及暂存撤销、重做和提交撤销。
14
+ - 支持 OpenCode V2 原生工具结果,以及迁移到 V2 后可识别的 V1 工具记录。
15
+
16
+ ## 界面展示
17
+
18
+ | 位置 | 展示内容 |
19
+ | --- | --- |
20
+ | 会话侧边栏 → **Changes** | 会话累计统计和有变更记录的文件。会话目录外的文件归入 **Other files**。 |
21
+ | 宽终端中的 **Change history** | 左侧是文件列表,右侧是所选文件的编号时间线和 Diff。可拖动分隔线调整列表宽度。 |
22
+ | 窄终端中的 **Change history** | 每次显示一个区域。打开文件查看时间线和 Diff,再通过 **‹ Files** 返回。 |
23
+
24
+ ## 从 npm 安装
25
+
26
+ 请使用本版本的兼容目标 **OpenCode CLI v2.4.2**。运行以下命令安装:
27
+
28
+ ```sh
29
+ opencode plugin add opencode-change-history@latest
30
+ ```
31
+
32
+ 也可以在 `~/.config/opencode/cli.json`(或 `$XDG_CONFIG_HOME/opencode/cli.json`)中加入同一配置项,保留已有设置:
33
+
34
+ ```json
35
+ {
36
+ "plugins": ["opencode-change-history@latest"]
37
+ }
38
+ ```
39
+
40
+ OpenCode 会安装 npm 包并加载它的 `./tui` TSX 入口。这是一个纯 TUI 插件,应配置在 `cli.json` 中。无需全局安装 npm 包、启动额外服务或执行构建。OpenCode 会监听 `cli.json`,需要时可用 `/reload` 强制重新加载。
41
+
42
+ ## 使用方法
43
+
44
+ 1. 打开或创建会话,显示会话侧边栏即可看到 **Changes**。
45
+ 2. 点击 **View details ›**、输入 `/changes`,或在命令面板选择 **Session change history**。快捷键为 `<leader>` 后按 `h`(默认 Leader 为 `Ctrl+X`)。点击侧边栏里的文件可直接打开它的最新修改记录。
46
+ 3. 使用 `Tab` / `Shift+Tab` 切换焦点。在文件列表中用方向键浏览、`Enter` 打开文件、`v` 切换树形/平铺视图、`s` 切换排序。在时间线中点击编号,或用 `←` / `→` 和 `Home` / `End` 切换记录。在 Diff 中用方向键滚动。`Page Up` / `Page Down` 在文件列表有焦点时滚动列表,其他情况下滚动 Diff。按 `r` 刷新,按 `Esc` 关闭弹窗。
47
+
48
+ ## 更新
49
+
50
+ 安装示例使用 `@latest`,由 OpenCode 管理更新。如果在 `cli.json` 中固定了版本,请将其替换为更新且兼容的版本。参阅 [OpenCode 插件文档](https://opencode.ai/docs/plugins#manage)。
51
+
52
+ ## 禁用或卸载
53
+
54
+ - **暂时禁用:**在 `cli.json` 中的安装项后面加入 `"-opencode-change-history"`。删除禁用项即可恢复。
55
+ - **卸载:**从 `cli.json` 中删除安装项和禁用项;或运行 `opencode plugin remove opencode-change-history@latest`(如果安装时使用了其他版本标识,请替换成实际使用的标识),再删除可能存在的禁用项。OpenCode 可能保留自己的包缓存和界面偏好,原有会话历史也仍保留在 OpenCode 中。
56
+
57
+ ## 工作原理
58
+
59
+ 插件通过 OpenCode V2 的公开客户端分页读取当前会话消息,从工具的成功结果中提取文件操作,在内存中汇总。工具完成事件会触发增量更新。切换会话会释放上一会话的内存历史;重连或手动刷新会从 OpenCode 重新读取。
60
+
61
+ 插件不通过 Git、快照、工作目录或 OpenCode 数据库重建变更。安装缓存由 OpenCode 管理,拖动分隔线时 OpenCode 会保存宽度偏好。插件不会单独存储变更历史。
62
+
63
+ ## 变更统计规则
64
+
65
+ - 统计的是历史修改量。先新增 10 行、随后删除同样的 10 行,累计为 **+10 / −10**。
66
+ - 成功的 `edit`、`patch`、`write`、迁移后的 `apply_patch`,以及 Code Mode `execute` 等提供明确文件变更元数据的工具,均可提供统计依据。失败或未完成的调用、没有结构化文件变更结果的 Shell 命令不计入。
67
+ - 已知行数计入确认统计。`?` 表示行数不完整;某一方向完全未知时可能省略。比例条仅使用已知行数。
68
+ - `~` 表示显示值含有根据已确认成功的 `write` 创建所提交文本推算的新增行数。估算值不计入确认统计。`Partial` 表示缺少完整 Diff 或行数;从工具输入生成的预览会明确标记,不能用于确认变更。
69
+ - 暂存撤销会隐藏受影响的历史,重做后恢复。提交撤销后,OpenCode 已删除的消息不再产生历史记录。分支显示 OpenCode 复制过来的历史;子代理的变更显示在各自会话中。
70
+
71
+ ## 已知限制
72
+
73
+ - 未被当前会话工具记录的编辑不可见。无法重建没有元数据的 Shell 变更,也无法重建工具报错前留下的文件变更。
74
+ - `write` 覆盖可能只记录操作,未记录 Diff。Code Mode 对记录数量和补丁大小有限制。
75
+ - 路径按词法归一化,无法事后解析未记录的工作目录、符号链接及跨环境别名。记录了来源和目标的移动归在目标路径下。
76
+
77
+ ## 兼容版本
78
+
79
+ 本版本面向 **OpenCode CLI v2.4.2**(OpenCode V2、OpenTUI 0.9.9、Solid 1.9.17)。本次发布验证不覆盖其他 OpenCode 版本或平台。OpenCode V1 不能作为宿主,本包也不提供桌面端或网页端界面。
80
+
81
+ ## 本地开发与测试
82
+
83
+ 在仓库根目录使用 Bun 1.4.2、Node.js/npm 和 `tar`:
84
+
85
+ ```sh
86
+ bun install --frozen-lockfile
87
+ bun test
88
+ bun run check
89
+ npm pack --dry-run
90
+ archive=$(npm pack)
91
+ node scripts/check-package.mjs "$archive"
92
+ ```
93
+
94
+ 如需在单次启动中加载源码,从要打开的项目目录执行以下命令,并将示例路径替换为插件仓库的绝对路径:
95
+
96
+ ```sh
97
+ OPENCODE_CLI_CONFIG_CONTENT='{"plugins":["/absolute/path/to/opencode-change-history"]}' opencode
98
+ ```
99
+
100
+ `src/core/` 的解析器处理会话消息和工具结果,不导入 SDK 或 TUI 运行时。`src/session-history.ts` 接入 SDK,`src/tui.tsx` 注册侧边栏和弹窗命令。参阅 [OpenCode TUI 插件开发文档](https://opencode.ai/docs/build/plugins/cli)和[变更日志](./CHANGELOG.zh-CN.md)。
101
+
102
+ ## 许可证
103
+
104
+ [MIT](./LICENSE)
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "opencode-change-history",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Browse recorded file changes and diffs for the current OpenCode terminal session.",
5
+ "type": "module",
6
+ "author": "Chenlong (https://github.com/chenlongapps)",
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/chenlongapps/opencode-change-history.git"
11
+ },
12
+ "homepage": "https://github.com/chenlongapps/opencode-change-history#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/chenlongapps/opencode-change-history/issues"
15
+ },
16
+ "keywords": ["opencode", "opencode-plugin", "tui", "change-history", "diff"],
17
+ "packageManager": "bun@1.4.2",
18
+ "exports": {
19
+ "./tui": "./src/tui.tsx"
20
+ },
21
+ "files": [
22
+ "README.zh-CN.md",
23
+ "CHANGELOG.md",
24
+ "CHANGELOG.zh-CN.md",
25
+ "src/tui.tsx",
26
+ "src/session-history.ts",
27
+ "src/core/diff.ts",
28
+ "src/core/history.ts",
29
+ "src/core/parser.ts",
30
+ "src/core/patch-input.ts",
31
+ "src/core/paths.ts",
32
+ "src/core/types.ts",
33
+ "src/ui/changes-sidebar.tsx",
34
+ "src/ui/changes.tsx",
35
+ "src/ui/diff-view.tsx",
36
+ "src/ui/explorer.tsx",
37
+ "src/ui/file-tree.ts",
38
+ "src/ui/history-nav.tsx",
39
+ "src/ui/layout.ts",
40
+ "src/ui/presentation.tsx"
41
+ ],
42
+ "scripts": {
43
+ "test": "bun test",
44
+ "check": "tsc --noEmit"
45
+ },
46
+ "dependencies": {
47
+ "@opencode/theme": "2.4.2"
48
+ },
49
+ "peerDependencies": {
50
+ "@opentui/core": "0.9.9",
51
+ "@opentui/solid": "0.9.9",
52
+ "solid-js": "1.9.17"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "@opentui/core": { "optional": true },
56
+ "@opentui/solid": { "optional": true },
57
+ "solid-js": { "optional": true }
58
+ },
59
+ "devDependencies": {
60
+ "@opencode/client": "2.4.2",
61
+ "@opencode/plugin": "2.4.2",
62
+ "@opentui/core": "0.9.9",
63
+ "@opentui/solid": "0.9.9",
64
+ "@types/bun": "^1.3.0",
65
+ "solid-js": "1.9.17",
66
+ "typescript": "^6.0.0"
67
+ },
68
+ "publishConfig": {
69
+ "registry": "https://registry.npmjs.org/",
70
+ "access": "public"
71
+ }
72
+ }
@@ -0,0 +1,54 @@
1
+ import type { LineCounts } from "./types"
2
+
3
+ export function unifiedCounts(patch: string): Required<LineCounts> | undefined {
4
+ let oldLines = 0
5
+ let newLines = 0
6
+ let additions = 0
7
+ let deletions = 0
8
+ let hunks = 0
9
+ for (const line of patch.replaceAll("\r\n", "\n").split("\n")) {
10
+ const header = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(?:.*)$/.exec(line)
11
+ if (header) {
12
+ if (oldLines || newLines) return
13
+ oldLines = Number(header[1] ?? 1)
14
+ newLines = Number(header[2] ?? 1)
15
+ hunks++
16
+ continue
17
+ }
18
+ if (line === "\") continue
19
+ if (!hunks) continue
20
+ if (!oldLines && !newLines && line === "") continue
21
+ switch (line[0]) {
22
+ case "+":
23
+ additions++
24
+ newLines--
25
+ break
26
+ case "-":
27
+ deletions++
28
+ oldLines--
29
+ break
30
+ case " ":
31
+ oldLines--
32
+ newLines--
33
+ break
34
+ default:
35
+ return
36
+ }
37
+ if (oldLines < 0 || newLines < 0) return
38
+ }
39
+ if (hunks && !oldLines && !newLines) return { additions, deletions }
40
+ }
41
+
42
+ /** A snippet for display. Its ranges are local to the snippet, not positions in the file. */
43
+ export function snippet(path: string, lines: readonly string[]): string | undefined {
44
+ if (!lines.some((line) => line.startsWith("+") || line.startsWith("-"))) return
45
+ const oldLines = lines.filter((line) => !line.startsWith("+")).length
46
+ const newLines = lines.filter((line) => !line.startsWith("-")).length
47
+ const label = path.replaceAll(/[\r\n\t]/g, " ")
48
+ return `--- ${label}\n+++ ${label}\n@@ -${oldLines ? 1 : 0},${oldLines} +${newLines ? 1 : 0},${newLines} @@\n${lines.join("\n")}\n`
49
+ }
50
+
51
+ export function prefixedLines(text: string, prefix: string): string[] {
52
+ if (!text) return []
53
+ return text.replaceAll("\r\n", "\n").replace(/\n$/, "").split("\n").map((line) => prefix + line)
54
+ }
@@ -0,0 +1,86 @@
1
+ import type { ParsedMessage } from "./parser"
2
+ import { filePath } from "./paths"
3
+ import type { FileHistory, History, RecordedChange, Statistics } from "./types"
4
+
5
+ function emptyStatistics(): Statistics {
6
+ return {
7
+ operations: 0, additions: 0, deletions: 0, estimatedAdditions: 0,
8
+ unknownAdditions: 0, unknownDeletions: 0, incomplete: 0,
9
+ }
10
+ }
11
+
12
+ export function sumStatistics(entries: Iterable<Statistics>): Statistics {
13
+ const total = emptyStatistics()
14
+ for (const entry of entries) {
15
+ total.operations += entry.operations
16
+ total.additions += entry.additions
17
+ total.deletions += entry.deletions
18
+ total.estimatedAdditions += entry.estimatedAdditions
19
+ total.unknownAdditions += entry.unknownAdditions
20
+ total.unknownDeletions += entry.unknownDeletions
21
+ total.incomplete += entry.incomplete
22
+ }
23
+ return total
24
+ }
25
+
26
+ function count(stats: Statistics, change: RecordedChange) {
27
+ stats.operations++
28
+ if (change.additions === undefined) stats.unknownAdditions++
29
+ else stats.additions += change.additions
30
+ if (change.deletions === undefined) stats.unknownDeletions++
31
+ else stats.deletions += change.deletions
32
+ if (change.estimatedAdditions !== undefined) stats.estimatedAdditions += change.estimatedAdditions
33
+ if (change.incomplete) stats.incomplete++
34
+ }
35
+
36
+ /** Consume messages in server sequence order, which also orders copied fork messages. */
37
+ export function aggregate(messages: readonly ParsedMessage[], directory: string, boundary?: string): History {
38
+ const stop = boundary === undefined ? -1 : messages.findIndex((message) => message.id === boundary)
39
+ const active = stop >= 0 ? messages.slice(0, stop) : messages
40
+ let location = messages.find((message) => message.type === "location-switched")?.previousDirectory ?? directory
41
+ let workingDirectory = location
42
+ const hasIdle = messages.some((message) => message.type === "idle")
43
+ let turn = 0
44
+ let inTurn = false
45
+ const files = new Map<string, FileHistory>()
46
+ const stats = emptyStatistics()
47
+ const seen = new Set<string>()
48
+
49
+ for (const message of active) {
50
+ if (message.directory) {
51
+ location = message.directory
52
+ workingDirectory = location
53
+ }
54
+ if (message.type === "idle") inTurn = false
55
+ if (message.type === "user" && (!hasIdle || !inTurn)) {
56
+ turn++
57
+ inTurn = true
58
+ }
59
+ for (const record of message.changes) {
60
+ if (seen.has(record.id)) continue
61
+ seen.add(record.id)
62
+ const path = filePath(record.path, workingDirectory)
63
+ const previousPath = record.previousPath === undefined ? undefined : filePath(record.previousPath, workingDirectory)
64
+ const change: RecordedChange = {
65
+ ...record,
66
+ path,
67
+ previousPath: previousPath === path ? undefined : previousPath,
68
+ kind: record.kind === "moved" && previousPath === path ? "modified" : record.kind,
69
+ turn: inTurn ? turn : undefined,
70
+ incomplete: record.diffQuality !== "recorded" || record.additions === undefined || record.deletions === undefined,
71
+ }
72
+ let file = files.get(path)
73
+ if (file === undefined) {
74
+ file = { path, lastModified: change.time, changes: [], ...emptyStatistics() }
75
+ files.set(path, file)
76
+ }
77
+ file.changes.push(change)
78
+ file.lastModified = Math.max(file.lastModified, change.time)
79
+ count(file, change)
80
+ count(stats, change)
81
+ }
82
+ if (message.nextCwd !== undefined) workingDirectory = message.nextCwd ?? location
83
+ }
84
+
85
+ return { ...stats, files: [...files.values()].sort((a, b) => a.path.localeCompare(b.path)), staged: boundary !== undefined }
86
+ }