pi-path-bar 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/LICENSE +21 -0
- package/README.md +187 -2
- package/README.zh-CN.md +188 -0
- package/THIRD_PARTY_NOTICES.md +67 -0
- package/package.json +55 -4
- package/src/config.ts +106 -0
- package/src/git.ts +139 -0
- package/src/index.ts +119 -0
- package/src/path.ts +76 -0
- package/src/settings.ts +69 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pi-path-bar 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,188 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-path-bar
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
English | [简体中文](README.zh-CN.md)
|
|
4
|
+
|
|
5
|
+
A Pi extension for compact directory paths, folder aliases, and theme-aware Git status.
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
~/C/P/demo-app ( main)
|
|
9
|
+
Projects/demo-app ( main +2 !1 ?3)
|
|
10
|
+
demo ( main ⇡1)
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- Short, automatic, and full path display modes.
|
|
16
|
+
- Display aliases for any folder, without changing actual paths or environment variables.
|
|
17
|
+
- Theme-aware alias colors and Tide-style Git status indicators.
|
|
18
|
+
- An interactive settings menu with persistent configuration.
|
|
19
|
+
- Existing usage statistics, model information, and extension status lines.
|
|
20
|
+
- Unicode folder names and aliases.
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
After the first npm release, install from npm:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
pi install npm:pi-path-bar
|
|
28
|
+
# Or try it for one run:
|
|
29
|
+
pi -e npm:pi-path-bar
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Before that release, or to use the Git source, install from GitHub:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
pi install git:github.com/johnbitcn/pi-path-bar
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Run `/reload` in an existing Pi session, then open `/path-bar`.
|
|
39
|
+
|
|
40
|
+
For a single Pi run:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pi -e git:github.com/johnbitcn/pi-path-bar
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
For local development, run from the project directory:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
pi install "$PWD"
|
|
50
|
+
# Or load the extension for one run:
|
|
51
|
+
pi -e ./src/index.ts
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Load only one copy of the extension. Remove an existing local or Git installation before switching sources. Folder icons require a Nerd Font; you can turn them off in settings.
|
|
55
|
+
|
|
56
|
+
## Settings
|
|
57
|
+
|
|
58
|
+
Run `/path-bar`. Use the arrow keys to select an item, Enter or Space to change a setting or open an action, and Esc to exit. Changes apply immediately and are saved automatically.
|
|
59
|
+
|
|
60
|
+
| Setting | Default | Choices |
|
|
61
|
+
| --- | --- | --- |
|
|
62
|
+
| Path display | Short | Short, Auto, Full, Native footer |
|
|
63
|
+
| Folder icon | On | On, Off |
|
|
64
|
+
| Git status | On | On, Off |
|
|
65
|
+
| Session name | On | On, Off |
|
|
66
|
+
| Add folder alias | — | Enter a folder path and a name |
|
|
67
|
+
| Manage folder aliases | — | Edit or delete aliases |
|
|
68
|
+
|
|
69
|
+
**Native footer** restores Pi's built-in footer. Other display settings are retained but do not apply in that mode.
|
|
70
|
+
|
|
71
|
+
### Path modes
|
|
72
|
+
|
|
73
|
+
- **Short:** always abbreviate intermediate folders to their first grapheme, including Unicode names.
|
|
74
|
+
- **Auto:** show the full path when it fits; otherwise abbreviate it.
|
|
75
|
+
- **Full:** do not abbreviate; truncate the line if needed.
|
|
76
|
+
|
|
77
|
+
Short and Auto collapse intermediate folders to `…` when necessary. At very small widths, the root and icon are dropped before the final folder name is truncated.
|
|
78
|
+
|
|
79
|
+
The home directory is shown as `~`. Named roots such as `~` and folder aliases receive a folder icon. Absolute paths starting with `/` do not.
|
|
80
|
+
|
|
81
|
+
## Folder aliases
|
|
82
|
+
|
|
83
|
+
Choose **Add folder alias** to name any folder. Enter an absolute path or a path starting with `~/`. Leave the path blank and press Enter to use the current directory. The target must exist and be a directory.
|
|
84
|
+
|
|
85
|
+
For example, name `~/CloudDrive` **Cloud**:
|
|
86
|
+
|
|
87
|
+
```text
|
|
88
|
+
Cloud
|
|
89
|
+
Cloud/P/demo-app
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
You can also name `~/CloudDrive/Projects/demo-app` **demo**. Then that folder displays as ` demo`, and its child displays as ` demo/src`.
|
|
93
|
+
|
|
94
|
+
### Matching and editing
|
|
95
|
+
|
|
96
|
+
- An alias matches its folder and descendants, at directory boundaries.
|
|
97
|
+
- If multiple aliases match, the longest path wins. Parent and child aliases are not combined.
|
|
98
|
+
- The alias name remains intact when possible. Descendant folders follow the selected path mode.
|
|
99
|
+
- Without a match, the extension uses `~` or an absolute path.
|
|
100
|
+
- Paths are normalized and `~` is expanded on save. Symbolic links are not resolved.
|
|
101
|
+
- Paths and names must be unique. Names cannot be empty, `~`, `.`, or `..`, or contain slashes, backslashes, newlines, or control characters.
|
|
102
|
+
- When editing, leave a field blank to keep its existing value. Esc cancels.
|
|
103
|
+
- Deleting an alias does not delete the folder. Stored aliases remain available when a drive is disconnected.
|
|
104
|
+
|
|
105
|
+
Only the matched alias name uses Pi's `mdLink` theme color: brighter blue in the built-in dark theme and darker blue in the light theme. Custom themes control their own link color. The icon, descendant path, and session name use gray; Git uses its status color. Colors follow theme changes.
|
|
106
|
+
|
|
107
|
+
Aliases affect only the footer. They do not change the working directory, tool paths, or environment variables.
|
|
108
|
+
|
|
109
|
+
## Git status
|
|
110
|
+
|
|
111
|
+
Git indicators borrow Tide's notation, but use Pi theme text colors rather than background colors. The extension does not modify fish or Tide.
|
|
112
|
+
|
|
113
|
+
| State | Theme token | Built-in appearance |
|
|
114
|
+
| --- | --- | --- |
|
|
115
|
+
| Initial loading or query failure | `text` | Default text color, with `?` |
|
|
116
|
+
| Clean working tree | `mdLink` | Blue |
|
|
117
|
+
| Staged, unstaged, or untracked changes | `warning` | Yellow |
|
|
118
|
+
| Conflicts or an active Git operation | `error` | Red |
|
|
119
|
+
|
|
120
|
+
Red takes priority over yellow, then blue. Outside a Git repository, Git information is hidden. Alias color is independent of Git status.
|
|
121
|
+
|
|
122
|
+
```text
|
|
123
|
+
demo ( main ⇣2 ⇡1 *1 ~2 +3 !4 ?5)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
| Indicator | Meaning |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `⇣N` | N commits behind upstream |
|
|
129
|
+
| `⇡N` | N commits ahead of upstream |
|
|
130
|
+
| `*N` | N stash entries |
|
|
131
|
+
| `~N` | N conflicted files; covers `DD AU UD UA DU AA UU` |
|
|
132
|
+
| `+N` | N staged entries |
|
|
133
|
+
| `!N` | N unstaged entries |
|
|
134
|
+
| `?N` | N untracked entries |
|
|
135
|
+
|
|
136
|
+
Zero counts are omitted. Untracked directories are grouped using Git's default behavior. Conflicts are not counted again as staged or unstaged changes. Ahead, behind, and stash counts alone do not change the color. Ahead and behind are omitted if no upstream exists.
|
|
137
|
+
|
|
138
|
+
Active operations include merge, rebase, cherry-pick, revert, and bisect. Rebase progress is shown when available. Detached HEAD displays `#tag` or `@short-commit`. Linked worktrees are supported.
|
|
139
|
+
|
|
140
|
+
Queries run asynchronously with a timeout. Status refreshes every five seconds, after tool execution or an agent turn, and when the branch changes. Disabling Git status or selecting Native footer stops the extension's queries.
|
|
141
|
+
|
|
142
|
+
## Configuration
|
|
143
|
+
|
|
144
|
+
Settings are shared across projects and stored in:
|
|
145
|
+
|
|
146
|
+
```text
|
|
147
|
+
~/.pi/agent/pi-path-bar.json
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
If `PI_CODING_AGENT_DIR` is set, its directory is used instead. The extension never sets or changes that variable.
|
|
151
|
+
|
|
152
|
+
```json
|
|
153
|
+
{
|
|
154
|
+
"mode": "short",
|
|
155
|
+
"icon": true,
|
|
156
|
+
"branch": true,
|
|
157
|
+
"session": true,
|
|
158
|
+
"aliases": [
|
|
159
|
+
{ "path": "/home/example/Projects", "name": "Projects" }
|
|
160
|
+
]
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The `branch` field controls Git status. Settings survive restarts and `/reload`. Opening the menu reloads the file. Saves use a temporary file and atomic replacement. Other running Pi instances must reopen the menu or reload to pick up changes.
|
|
165
|
+
|
|
166
|
+
If the new file is absent, the extension reads the legacy `pi-show-dir.json`. The next save writes the new file and leaves the old file intact. Invalid configuration is reported and is not overwritten.
|
|
167
|
+
|
|
168
|
+
## Limitations
|
|
169
|
+
|
|
170
|
+
- Pi's public API replaces the entire footer. If another extension also calls `setFooter()`, the last one wins.
|
|
171
|
+
- The public API does not expose the auto-compaction setting, so the custom footer does not show the native `(auto)` marker.
|
|
172
|
+
- This is an unofficial Pi extension. It is not affiliated with or endorsed by Pi or Tide.
|
|
173
|
+
|
|
174
|
+
## Development
|
|
175
|
+
|
|
176
|
+
Requires Node.js 22.19 or newer and Git for Git status and integration tests.
|
|
177
|
+
|
|
178
|
+
```sh
|
|
179
|
+
npm install --ignore-scripts
|
|
180
|
+
npm test
|
|
181
|
+
npm run check
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## License and acknowledgments
|
|
185
|
+
|
|
186
|
+
[MIT](LICENSE). See [Third-party notices](THIRD_PARTY_NOTICES.md) for Pi and Tide copyright and license texts. Host packages and font files are not bundled.
|
|
187
|
+
|
|
188
|
+
Maintainers: see the [npm release guide](https://github.com/johnbitcn/pi-path-bar/blob/main/RELEASING.md) for authentication, packaging checks, publishing, and verification.
|
package/README.zh-CN.md
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# pi-path-bar
|
|
2
|
+
|
|
3
|
+
[English](README.md) | 简体中文
|
|
4
|
+
|
|
5
|
+
Pi 底栏扩展。支持简短路径、目录别名和随主题调整的 Git 状态颜色。
|
|
6
|
+
|
|
7
|
+
```text
|
|
8
|
+
~/C/P/demo-app ( main)
|
|
9
|
+
Projects/demo-app ( main +2 !1 ?3)
|
|
10
|
+
demo ( main ⇡1)
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## 功能
|
|
14
|
+
|
|
15
|
+
- 简短、自动和完整路径显示模式。
|
|
16
|
+
- 为任意文件夹设置显示别名,不改变实际路径或环境变量。
|
|
17
|
+
- 随主题调整的别名颜色,以及 Tide 风格的 Git 状态标记。
|
|
18
|
+
- 交互式设置菜单,自动保存配置。
|
|
19
|
+
- 保留用量统计、模型信息和其他扩展的状态行。
|
|
20
|
+
- 支持中文等 Unicode 目录名和别名。
|
|
21
|
+
|
|
22
|
+
## 安装
|
|
23
|
+
|
|
24
|
+
首次发布到 npm 后,可以从 npm 安装:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
pi install npm:pi-path-bar
|
|
28
|
+
# 或仅在本次启动中使用:
|
|
29
|
+
pi -e npm:pi-path-bar
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
首次发布前,或需要使用 Git 来源时,从 GitHub 安装:
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
pi install git:github.com/johnbitcn/pi-path-bar
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
在已运行的 Pi 中执行 `/reload`,再输入 `/path-bar`。
|
|
39
|
+
|
|
40
|
+
仅在本次启动中使用:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pi -e git:github.com/johnbitcn/pi-path-bar
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
本地开发时,在项目目录执行:
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
pi install "$PWD"
|
|
50
|
+
# 或仅在本次启动中加载扩展:
|
|
51
|
+
pi -e ./src/index.ts
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
只加载一份扩展。切换安装来源前,先移除已有的本地或 Git 安装。目录图标需要 Nerd Font;也可在设置中关闭图标。
|
|
55
|
+
|
|
56
|
+
## 设置
|
|
57
|
+
|
|
58
|
+
执行 `/path-bar`。上下键选择,Enter 或空格切换设置或打开操作,Esc 退出。修改立即生效,并自动保存。扩展界面使用英文。
|
|
59
|
+
|
|
60
|
+
| 设置项 | 默认值 | 可选值 |
|
|
61
|
+
| --- | --- | --- |
|
|
62
|
+
| Path display(路径显示) | Short | Short、Auto、Full、Native footer |
|
|
63
|
+
| Folder icon(目录图标) | On | On、Off |
|
|
64
|
+
| Git status(Git 状态) | On | On、Off |
|
|
65
|
+
| Session name(会话名称) | On | On、Off |
|
|
66
|
+
| Add folder alias(添加目录别名) | — | 输入文件夹路径和名称 |
|
|
67
|
+
| Manage folder aliases(管理目录别名) | — | 修改或删除别名 |
|
|
68
|
+
|
|
69
|
+
**Native footer** 恢复 Pi 原生底栏。其他显示设置会保留,但在该模式下不生效。
|
|
70
|
+
|
|
71
|
+
### 路径显示模式
|
|
72
|
+
|
|
73
|
+
- **Short:**始终将中间目录缩写为首个字素,支持中文等 Unicode 名称。
|
|
74
|
+
- **Auto:**宽度足够时显示完整路径,否则缩写。
|
|
75
|
+
- **Full:**不缩写,超出宽度时截断。
|
|
76
|
+
|
|
77
|
+
Short 和 Auto 在宽度不足时将中间目录折叠为 `…`。极窄时,先省略起点与图标,再截断最后一级目录名。
|
|
78
|
+
|
|
79
|
+
主目录显示为 `~`。`~` 和目录别名等命名起点前显示目录图标。以 `/` 开头的绝对路径不显示图标。
|
|
80
|
+
|
|
81
|
+
## 目录别名
|
|
82
|
+
|
|
83
|
+
选择 **Add folder alias**,可以给任意文件夹命名。输入绝对路径或 `~/` 开头的路径。路径留空直接按 Enter,则使用当前目录。目标必须存在且为文件夹。
|
|
84
|
+
|
|
85
|
+
例如,将 `~/CloudDrive` 命名为 **Cloud**:
|
|
86
|
+
|
|
87
|
+
```text
|
|
88
|
+
Cloud
|
|
89
|
+
Cloud/P/demo-app
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
也可以将 `~/CloudDrive/Projects/demo-app` 命名为 **demo**。该目录显示为 ` demo`,其子目录显示为 ` demo/src`。
|
|
93
|
+
|
|
94
|
+
### 匹配和编辑规则
|
|
95
|
+
|
|
96
|
+
- 别名匹配该目录及其子目录,按目录边界匹配。
|
|
97
|
+
- 多个别名同时匹配时,使用最长路径。父级和子级别名不会叠加。
|
|
98
|
+
- 宽度允许时保留完整别名。其后的目录按所选模式处理。
|
|
99
|
+
- 没有匹配时,使用 `~` 或绝对路径。
|
|
100
|
+
- 保存时规范化路径并展开 `~`,但不解析符号链接。
|
|
101
|
+
- 路径和名称不能重复。名称不能为空、`~`、`.` 或 `..`,不能包含斜杠、反斜杠、换行或控制字符。
|
|
102
|
+
- 修改时,字段留空表示保留原值。Esc 取消。
|
|
103
|
+
- 删除别名不会删除实际文件夹。磁盘暂时离线时,已有别名仍会保留。
|
|
104
|
+
|
|
105
|
+
仅命中的别名名称使用 Pi 主题的 `mdLink` 色。内置暗色主题使用较亮的蓝色,亮色主题使用较深的蓝色。自定义主题以其链接色为准。图标、子目录和会话名使用灰色;Git 信息使用状态色。切换主题后颜色同步更新。
|
|
106
|
+
|
|
107
|
+
别名只影响底栏,不改变工作目录、工具访问路径或环境变量。
|
|
108
|
+
|
|
109
|
+
## Git 状态
|
|
110
|
+
|
|
111
|
+
借用 Tide 的标记形式,但使用 Pi 主题文字色,不使用背景色。扩展不会修改 fish 或 Tide。
|
|
112
|
+
|
|
113
|
+
| 状态 | 主题色 | 内置主题效果 |
|
|
114
|
+
| --- | --- | --- |
|
|
115
|
+
| 初次读取或查询失败 | `text` | 默认文字色,显示 `?` |
|
|
116
|
+
| 工作区干净 | `mdLink` | 蓝色 |
|
|
117
|
+
| 有已暂存、未暂存或未跟踪变更 | `warning` | 黄色 |
|
|
118
|
+
| 有冲突或正在进行 Git 操作 | `error` | 红色 |
|
|
119
|
+
|
|
120
|
+
优先级:红色 > 黄色 > 蓝色。不在 Git 仓库时隐藏 Git 信息。目录别名颜色不受 Git 状态影响。
|
|
121
|
+
|
|
122
|
+
```text
|
|
123
|
+
demo ( main ⇣2 ⇡1 *1 ~2 +3 !4 ?5)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
| 标记 | 含义 |
|
|
127
|
+
| --- | --- |
|
|
128
|
+
| `⇣N` | 落后上游 N 个提交 |
|
|
129
|
+
| `⇡N` | 领先上游 N 个提交 |
|
|
130
|
+
| `*N` | N 条 stash |
|
|
131
|
+
| `~N` | N 个冲突文件,覆盖 `DD AU UD UA DU AA UU` |
|
|
132
|
+
| `+N` | N 个已暂存条目 |
|
|
133
|
+
| `!N` | N 个未暂存条目 |
|
|
134
|
+
| `?N` | N 个未跟踪条目 |
|
|
135
|
+
|
|
136
|
+
数量为零时不显示。未跟踪目录按 Git 默认行为合并为一个条目。冲突文件不重复计入已暂存或未暂存数量。领先、落后和 stash 本身不改变颜色。没有上游时,不显示领先和落后。
|
|
137
|
+
|
|
138
|
+
显示 merge、rebase、cherry-pick、revert、bisect 等操作。可用时显示 rebase 进度。分离 HEAD 时显示 `#标签` 或 `@提交短哈希`。支持 linked worktree。
|
|
139
|
+
|
|
140
|
+
查询异步执行,并设有超时。每 5 秒刷新一次,也在工具执行完成、agent 回复完成或分支变化时刷新。关闭 Git 状态或选择 Native footer 后,停止扩展查询。
|
|
141
|
+
|
|
142
|
+
## 配置
|
|
143
|
+
|
|
144
|
+
配置在各项目间共用,保存到:
|
|
145
|
+
|
|
146
|
+
```text
|
|
147
|
+
~/.pi/agent/pi-path-bar.json
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
若设置了 `PI_CODING_AGENT_DIR`,则使用该目录。扩展不会设置或修改此变量。
|
|
151
|
+
|
|
152
|
+
```json
|
|
153
|
+
{
|
|
154
|
+
"mode": "short",
|
|
155
|
+
"icon": true,
|
|
156
|
+
"branch": true,
|
|
157
|
+
"session": true,
|
|
158
|
+
"aliases": [
|
|
159
|
+
{ "path": "/home/example/Projects", "name": "Projects" }
|
|
160
|
+
]
|
|
161
|
+
}
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
`branch` 字段控制 Git 状态显示。配置在重启或 `/reload` 后保留。打开菜单时重新读取文件。保存使用临时文件和原子替换。其他已运行的 Pi 实例需要重新打开菜单或重新加载,才能同步修改。
|
|
165
|
+
|
|
166
|
+
新文件不存在时,会读取旧的 `pi-show-dir.json`。下次保存时写入新文件,并保留旧文件。配置损坏时会提示错误,不会覆盖原文件。
|
|
167
|
+
|
|
168
|
+
## 限制
|
|
169
|
+
|
|
170
|
+
- Pi 的公开 API 会替换整个底栏。其他扩展也调用 `setFooter()` 时,最后设置的底栏生效。
|
|
171
|
+
- 公开 API 不提供自动压缩开关,因此自定义底栏不显示原生 `(auto)` 标记。
|
|
172
|
+
- 这是非官方 Pi 扩展,与 Pi 或 Tide 项目无隶属或背书关系。
|
|
173
|
+
|
|
174
|
+
## 开发
|
|
175
|
+
|
|
176
|
+
需要 Node.js 22.19 或更新版本。Git 状态和集成测试需要 Git。
|
|
177
|
+
|
|
178
|
+
```sh
|
|
179
|
+
npm install --ignore-scripts
|
|
180
|
+
npm test
|
|
181
|
+
npm run check
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## 许可证与致谢
|
|
185
|
+
|
|
186
|
+
本项目采用 [MIT 许可证](LICENSE)。Pi 和 Tide 的版权及许可文本见[第三方声明](THIRD_PARTY_NOTICES.md)。发布包不包含宿主依赖或字体文件。
|
|
187
|
+
|
|
188
|
+
维护者可参阅 [npm 发布指南](https://github.com/johnbitcn/pi-path-bar/blob/main/RELEASING.md),了解登录、打包检查、发布和验证流程。
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
pi-path-bar is licensed under the MIT License. The following notices apply to upstream material referenced or adapted by this project. They do not imply endorsement.
|
|
4
|
+
|
|
5
|
+
## Pi
|
|
6
|
+
|
|
7
|
+
- Project: https://github.com/earendil-works/pi
|
|
8
|
+
- License source: https://github.com/earendil-works/pi/blob/main/LICENSE
|
|
9
|
+
- Material: extension settings UI patterns and footer display/usage formatting logic in `src/settings.ts` and `src/index.ts`.
|
|
10
|
+
- The Pi host supplies `@earendil-works/pi-coding-agent` and `@earendil-works/pi-tui`. Their package contents are not bundled in this npm package.
|
|
11
|
+
|
|
12
|
+
```text
|
|
13
|
+
MIT License
|
|
14
|
+
|
|
15
|
+
Copyright (c) 2025 Mario Zechner
|
|
16
|
+
|
|
17
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
18
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
19
|
+
in the Software without restriction, including without limitation the rights
|
|
20
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
21
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
22
|
+
furnished to do so, subject to the following conditions:
|
|
23
|
+
|
|
24
|
+
The above copyright notice and this permission notice shall be included in all
|
|
25
|
+
copies or substantial portions of the Software.
|
|
26
|
+
|
|
27
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
28
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
29
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
30
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
31
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
32
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
33
|
+
SOFTWARE.
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Tide
|
|
37
|
+
|
|
38
|
+
- Project: https://github.com/IlanCosman/tide
|
|
39
|
+
- License source: https://github.com/IlanCosman/tide/blob/v6/LICENSE.md
|
|
40
|
+
- Material: Git status notation and operation detection logic adapted from `_tide_item_git.fish` in `src/git.ts`. The TypeScript implementation uses porcelain v2 and handles all unmerged states.
|
|
41
|
+
- Tide is not bundled or required at runtime.
|
|
42
|
+
|
|
43
|
+
# MIT License
|
|
44
|
+
|
|
45
|
+
Copyright © `2020` `Ilan Cosman`
|
|
46
|
+
|
|
47
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
48
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
49
|
+
in the Software without restriction, including without limitation the rights
|
|
50
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
51
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
52
|
+
furnished to do so, subject to the following conditions:
|
|
53
|
+
|
|
54
|
+
The above copyright notice and this permission notice shall be included in all
|
|
55
|
+
copies or substantial portions of the Software.
|
|
56
|
+
|
|
57
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
58
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
59
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
60
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
61
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
62
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
63
|
+
SOFTWARE.
|
|
64
|
+
|
|
65
|
+
## Fonts and icons
|
|
66
|
+
|
|
67
|
+
The extension uses Unicode characters, including Nerd Font icon code points. No font files, icon images, or other font assets are bundled. Users supply their terminal font separately.
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-path-bar",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "A Pi extension for compact paths, folder aliases, and theme-aware Git status",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/johnbitcn/pi-path-bar.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/johnbitcn/pi-path-bar#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/johnbitcn/pi-path-bar/issues"
|
|
14
|
+
},
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=22.19.0"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public",
|
|
20
|
+
"registry": "https://registry.npmjs.org/"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"src/",
|
|
24
|
+
"README.md",
|
|
25
|
+
"README.zh-CN.md",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"THIRD_PARTY_NOTICES.md"
|
|
28
|
+
],
|
|
29
|
+
"keywords": [
|
|
30
|
+
"pi-package",
|
|
31
|
+
"pi-extension",
|
|
32
|
+
"terminal",
|
|
33
|
+
"git",
|
|
34
|
+
"path",
|
|
35
|
+
"footer"
|
|
36
|
+
],
|
|
37
|
+
"pi": {
|
|
38
|
+
"extensions": [
|
|
39
|
+
"./src/index.ts"
|
|
40
|
+
]
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"check": "tsc --noEmit",
|
|
44
|
+
"test": "node --experimental-strip-types --test test/*.test.ts",
|
|
45
|
+
"prepublishOnly": "npm run check && npm test"
|
|
46
|
+
},
|
|
47
|
+
"peerDependencies": {
|
|
48
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
49
|
+
"@earendil-works/pi-tui": "*"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@earendil-works/pi-coding-agent": "^1.1.0",
|
|
53
|
+
"@earendil-works/pi-tui": "^1.1.0",
|
|
54
|
+
"@types/node": "^26.6.4",
|
|
55
|
+
"typescript": "^7.0.2"
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/config.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
|
|
6
|
+
export type PathMode = "short" | "auto" | "full" | "native";
|
|
7
|
+
export interface FolderAlias { path: string; name: string }
|
|
8
|
+
export interface Config {
|
|
9
|
+
mode: PathMode;
|
|
10
|
+
icon: boolean;
|
|
11
|
+
branch: boolean;
|
|
12
|
+
session: boolean;
|
|
13
|
+
aliases: FolderAlias[];
|
|
14
|
+
}
|
|
15
|
+
export const defaults = (): Config => ({ mode: "short", icon: true, branch: true, session: true, aliases: [] });
|
|
16
|
+
|
|
17
|
+
export function aliasName(value: string): string {
|
|
18
|
+
const name = value.trim();
|
|
19
|
+
if (!name || name === "~" || name === "." || name === ".." || /[/\\\x00-\x1f\x7f-\x9f]/u.test(value)) {
|
|
20
|
+
throw new Error("Enter a nonempty name other than '~', '.', or '..'. Do not use slashes, backslashes, newlines, or control characters.");
|
|
21
|
+
}
|
|
22
|
+
return name;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function folderPath(value: string, home = homedir()): string {
|
|
26
|
+
const input = value.trim();
|
|
27
|
+
if (!input || /[\x00-\x1f\x7f-\x9f]/u.test(input)) throw new Error("Enter a valid folder path.");
|
|
28
|
+
const expanded = input === "~" ? home : input.startsWith("~/") ? join(home, input.slice(2)) : input;
|
|
29
|
+
if (!isAbsolute(expanded)) throw new Error("Use an absolute path or a path starting with ~/.");
|
|
30
|
+
const path = resolve(expanded);
|
|
31
|
+
try {
|
|
32
|
+
if (!statSync(path).isDirectory()) throw new Error();
|
|
33
|
+
} catch { throw new Error("The folder does not exist, or the path is not a directory."); }
|
|
34
|
+
return path;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function validateConfig(value: unknown): Config {
|
|
38
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The configuration must be a JSON object.");
|
|
39
|
+
const data = value as Record<string, unknown>;
|
|
40
|
+
const config = defaults();
|
|
41
|
+
if (data.mode !== undefined) {
|
|
42
|
+
if (!["short", "auto", "full", "native"].includes(data.mode as string)) throw new Error("Invalid path display mode.");
|
|
43
|
+
config.mode = data.mode as PathMode;
|
|
44
|
+
}
|
|
45
|
+
for (const key of ["icon", "branch", "session"] as const) {
|
|
46
|
+
if (data[key] === undefined) continue;
|
|
47
|
+
if (typeof data[key] !== "boolean") throw new Error(`${key} must be a boolean.`);
|
|
48
|
+
config[key] = data[key];
|
|
49
|
+
}
|
|
50
|
+
if (data.aliases !== undefined) {
|
|
51
|
+
if (!Array.isArray(data.aliases)) throw new Error("aliases must be an array.");
|
|
52
|
+
const paths = new Set<string>();
|
|
53
|
+
const names = new Set<string>();
|
|
54
|
+
config.aliases = data.aliases.map((item: unknown) => {
|
|
55
|
+
const alias = item as FolderAlias | undefined;
|
|
56
|
+
if (!alias || typeof alias.path !== "string" || !isAbsolute(alias.path) || /[\x00-\x1f\x7f-\x9f]/u.test(alias.path) || typeof alias.name !== "string") {
|
|
57
|
+
throw new Error("Invalid folder alias format.");
|
|
58
|
+
}
|
|
59
|
+
const path = resolve(alias.path);
|
|
60
|
+
const name = aliasName(alias.name);
|
|
61
|
+
if (paths.has(path) || names.has(name)) throw new Error("Folder paths and alias names must be unique.");
|
|
62
|
+
paths.add(path); names.add(name);
|
|
63
|
+
// Do not stat stored paths: a disconnected drive should not invalidate all settings.
|
|
64
|
+
return { path, name };
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
return config;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class ConfigStore {
|
|
71
|
+
readonly file: string;
|
|
72
|
+
readonly legacyFile?: string;
|
|
73
|
+
constructor(file: string, legacyFile?: string) { this.file = file; this.legacyFile = legacyFile; }
|
|
74
|
+
load(): Config {
|
|
75
|
+
let text: string;
|
|
76
|
+
try { text = readFileSync(this.file, "utf8"); }
|
|
77
|
+
catch (error) {
|
|
78
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
79
|
+
return this.legacyFile ? new ConfigStore(this.legacyFile).load() : defaults();
|
|
80
|
+
}
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
return validateConfig(JSON.parse(text));
|
|
84
|
+
}
|
|
85
|
+
update(change: (config: Config) => void): Config {
|
|
86
|
+
// Read the latest disk state before each edit; preserve unrelated changes from other panes.
|
|
87
|
+
const config = this.load();
|
|
88
|
+
change(config);
|
|
89
|
+
const next = validateConfig(config);
|
|
90
|
+
mkdirSync(dirname(this.file), { recursive: true });
|
|
91
|
+
const temporary = `${this.file}.${randomUUID()}.tmp`;
|
|
92
|
+
try {
|
|
93
|
+
writeFileSync(temporary, JSON.stringify(next, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
|
94
|
+
renameSync(temporary, this.file);
|
|
95
|
+
} finally { rmSync(temporary, { force: true }); }
|
|
96
|
+
return next;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function setAlias(config: Config, alias: FolderAlias, previousPath?: string): void {
|
|
101
|
+
if (config.aliases.some((item) => item.path !== previousPath && (item.path === alias.path || item.name === alias.name))) {
|
|
102
|
+
throw new Error("This path or name already has an alias. Edit it in Manage folder aliases.");
|
|
103
|
+
}
|
|
104
|
+
config.aliases = config.aliases.filter((item) => item.path !== previousPath);
|
|
105
|
+
config.aliases.push(alias);
|
|
106
|
+
}
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFile, stat } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
export interface GitCounts { behind: number; ahead: number; stash: number; conflicted: number; staged: number; dirty: number; untracked: number }
|
|
6
|
+
export interface ReadyGit extends GitCounts { kind: "ready"; head: string; detached: boolean; oid: string; operation?: string }
|
|
7
|
+
export type GitState = ReadyGit | { kind: "none" } | { kind: "unknown" };
|
|
8
|
+
export type GitColor = "text" | "mdLink" | "warning" | "error";
|
|
9
|
+
const conflicts = new Set(["DD", "AU", "UD", "UA", "DU", "AA", "UU"]);
|
|
10
|
+
const safe = (value: string) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
|
|
11
|
+
|
|
12
|
+
/** Parse NUL-delimited porcelain v2 without interpreting filenames as records. */
|
|
13
|
+
export function parseStatus(output: string): ReadyGit {
|
|
14
|
+
const result: ReadyGit = { kind: "ready", head: "", detached: false, oid: "", behind: 0, ahead: 0, stash: 0, conflicted: 0, staged: 0, dirty: 0, untracked: 0 };
|
|
15
|
+
const records = output.split("\0");
|
|
16
|
+
for (let i = 0; i < records.length; i++) {
|
|
17
|
+
const record = records[i];
|
|
18
|
+
if (record.startsWith("# branch.head ")) {
|
|
19
|
+
result.head = record.slice(14); result.detached = result.head === "(detached)";
|
|
20
|
+
} else if (record.startsWith("# branch.oid ")) result.oid = record.slice(13);
|
|
21
|
+
else if (record.startsWith("# branch.ab ")) {
|
|
22
|
+
const counts = /^# branch\.ab \+(\d+) -(\d+)$/.exec(record);
|
|
23
|
+
if (counts) { result.ahead = Number(counts[1]); result.behind = Number(counts[2]); }
|
|
24
|
+
} else if (record.startsWith("# stash ")) result.stash = Number(record.slice(8)) || 0;
|
|
25
|
+
else if (record.startsWith("? ")) result.untracked++;
|
|
26
|
+
else if (/^[12u] /.test(record)) {
|
|
27
|
+
const xy = record.slice(2, 4);
|
|
28
|
+
if (record[0] === "u" || conflicts.has(xy)) result.conflicted++;
|
|
29
|
+
else {
|
|
30
|
+
if (xy[0] !== ".") result.staged++;
|
|
31
|
+
if (xy[1] !== ".") result.dirty++;
|
|
32
|
+
}
|
|
33
|
+
if (record[0] === "2") i++; // A rename/copy has a separate original-path record.
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
if (!result.head) throw new Error("Missing Git branch header");
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function gitColor(state: GitState): GitColor {
|
|
41
|
+
if (state.kind !== "ready") return "text";
|
|
42
|
+
if (state.operation || state.conflicted) return "error";
|
|
43
|
+
if (state.staged || state.dirty || state.untracked) return "warning";
|
|
44
|
+
return "mdLink";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function gitText(state: GitState, fallbackBranch?: string): string {
|
|
48
|
+
if (state.kind === "none") return "";
|
|
49
|
+
if (state.kind === "unknown") return ` ${fallbackBranch ? safe(fallbackBranch) + " " : ""}?`;
|
|
50
|
+
const parts = [` ${safe(state.head)}`];
|
|
51
|
+
if (state.operation) parts.push(state.operation);
|
|
52
|
+
for (const [key, symbol] of [["behind", "⇣"], ["ahead", "⇡"], ["stash", "*"], ["conflicted", "~"], ["staged", "+"], ["dirty", "!"], ["untracked", "?"]] as const) {
|
|
53
|
+
if (state[key]) parts.push(symbol + state[key]);
|
|
54
|
+
}
|
|
55
|
+
return parts.join(" ");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface CommandResult { stdout: string; stderr: string; code: number }
|
|
59
|
+
function git(cwd: string, args: string[], signal?: AbortSignal): Promise<CommandResult> {
|
|
60
|
+
return new Promise((resolve) => {
|
|
61
|
+
execFile("git", ["--no-optional-locks", "-C", cwd, ...args], {
|
|
62
|
+
encoding: "utf8", timeout: 3000, maxBuffer: 8 * 1024 * 1024, signal,
|
|
63
|
+
env: { ...process.env, LC_ALL: "C", GIT_TERMINAL_PROMPT: "0" },
|
|
64
|
+
}, (error, stdout, stderr) => resolve({ stdout, stderr, code: error ? (typeof error.code === "number" ? error.code : -1) : 0 }));
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async function exists(path: string): Promise<boolean> {
|
|
68
|
+
try { await stat(path); return true; }
|
|
69
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; }
|
|
70
|
+
}
|
|
71
|
+
async function text(path: string): Promise<string> {
|
|
72
|
+
try { return (await readFile(path, "utf8")).trim(); }
|
|
73
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return ""; throw error; }
|
|
74
|
+
}
|
|
75
|
+
export async function readOperation(gitDir: string): Promise<string | undefined> {
|
|
76
|
+
for (const directory of ["rebase-merge", "rebase-apply"]) {
|
|
77
|
+
if (!await exists(join(gitDir, directory))) continue;
|
|
78
|
+
const base = join(gitDir, directory);
|
|
79
|
+
const name = directory === "rebase-merge"
|
|
80
|
+
? (await exists(join(base, "interactive")) ? "rebase-i" : "rebase-m")
|
|
81
|
+
: await exists(join(base, "rebasing")) ? "rebase" : await exists(join(base, "applying")) ? "am" : "am/rebase";
|
|
82
|
+
const step = await text(join(base, directory === "rebase-merge" ? "msgnum" : "next"));
|
|
83
|
+
const total = await text(join(base, directory === "rebase-merge" ? "end" : "last"));
|
|
84
|
+
return name + (/^\d+$/.test(step) && /^\d+$/.test(total) ? ` ${step}/${total}` : "");
|
|
85
|
+
}
|
|
86
|
+
for (const [file, name] of [["MERGE_HEAD", "merge"], ["CHERRY_PICK_HEAD", "cherry-pick"], ["REVERT_HEAD", "revert"], ["BISECT_LOG", "bisect"]]) {
|
|
87
|
+
if (await exists(join(gitDir, file))) return name;
|
|
88
|
+
}
|
|
89
|
+
// A multi-commit cherry-pick/revert can be between commits with no *_HEAD file.
|
|
90
|
+
if (await exists(join(gitDir, "sequencer"))) {
|
|
91
|
+
const todo = await text(join(gitDir, "sequencer", "todo"));
|
|
92
|
+
return todo.startsWith("revert ") ? "revert" : "cherry-pick";
|
|
93
|
+
}
|
|
94
|
+
return undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function readGit(cwd: string, signal?: AbortSignal): Promise<GitState> {
|
|
98
|
+
try {
|
|
99
|
+
const directory = await git(cwd, ["rev-parse", "--absolute-git-dir"], signal);
|
|
100
|
+
if (directory.code !== 0) return { kind: directory.stderr.includes("not a git repository") ? "none" : "unknown" };
|
|
101
|
+
const status = await git(cwd, ["status", "--porcelain=v2", "-z", "--branch", "--show-stash", "--untracked-files=normal"], signal);
|
|
102
|
+
if (status.code !== 0) return { kind: "unknown" };
|
|
103
|
+
const result = parseStatus(status.stdout);
|
|
104
|
+
const gitDir = directory.stdout.trimEnd();
|
|
105
|
+
result.operation = await readOperation(gitDir);
|
|
106
|
+
if (result.detached) {
|
|
107
|
+
const tag = await git(cwd, ["describe", "--tags", "--exact-match", "HEAD"], signal);
|
|
108
|
+
result.head = tag.code === 0 ? `#${tag.stdout.trimEnd()}` : `@${result.oid.slice(0, 7)}`;
|
|
109
|
+
}
|
|
110
|
+
return result;
|
|
111
|
+
} catch { return { kind: "unknown" }; }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** One query at a time. Disposal aborts children and suppresses late results. */
|
|
115
|
+
export function watchGit(cwd: string, changed: () => void, intervalMs = 5000, read = readGit) {
|
|
116
|
+
let value: GitState = { kind: "unknown" };
|
|
117
|
+
let stopped = false, running = false, queued = false;
|
|
118
|
+
const controller = new AbortController();
|
|
119
|
+
const refresh = async () => {
|
|
120
|
+
if (stopped) return;
|
|
121
|
+
if (running) { queued = true; return; }
|
|
122
|
+
running = true;
|
|
123
|
+
try {
|
|
124
|
+
const next = await read(cwd, controller.signal).catch(() => ({ kind: "unknown" } as GitState));
|
|
125
|
+
if (!stopped && JSON.stringify(next) !== JSON.stringify(value)) { value = next; changed(); }
|
|
126
|
+
} finally {
|
|
127
|
+
running = false;
|
|
128
|
+
if (queued && !stopped) { queued = false; void refresh(); }
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
const timer = setInterval(() => { void refresh(); }, intervalMs);
|
|
132
|
+
timer.unref();
|
|
133
|
+
void refresh();
|
|
134
|
+
return {
|
|
135
|
+
get value() { return value; },
|
|
136
|
+
refresh: () => { void refresh(); },
|
|
137
|
+
dispose: () => { stopped = true; clearInterval(timer); controller.abort(); },
|
|
138
|
+
};
|
|
139
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { ConfigStore, defaults, type Config } from "./config.ts";
|
|
5
|
+
import { openSettings } from "./settings.ts";
|
|
6
|
+
import { gitColor, gitText, watchGit } from "./git.ts";
|
|
7
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
9
|
+
import { directoryLine, resolveDisplayPath } from "./path.ts";
|
|
10
|
+
|
|
11
|
+
const tokens = (n: number) => n < 1000 ? String(n) : n < 1e6 ? `${(n / 1000).toFixed(1)}k` : `${(n / 1e6).toFixed(1)}M`;
|
|
12
|
+
|
|
13
|
+
export default function (pi: ExtensionAPI, configFile = join(getAgentDir(), "pi-path-bar.json")) {
|
|
14
|
+
const store = new ConfigStore(configFile, configFile === join(getAgentDir(), "pi-path-bar.json") ? join(getAgentDir(), "pi-show-dir.json") : undefined);
|
|
15
|
+
let config = defaults();
|
|
16
|
+
const load = (ctx: ExtensionContext) => {
|
|
17
|
+
try { config = store.load(); }
|
|
18
|
+
catch (error) { ctx.ui.notify(`Cannot read ${store.file}: ${error instanceof Error ? error.message : String(error)}. The file will not be overwritten.`, "error"); }
|
|
19
|
+
};
|
|
20
|
+
let activeGit: ReturnType<typeof watchGit> | undefined;
|
|
21
|
+
const install = (ctx: ExtensionContext) => {
|
|
22
|
+
activeGit?.dispose();
|
|
23
|
+
activeGit = undefined;
|
|
24
|
+
if (ctx.mode !== "tui") return;
|
|
25
|
+
if (config.mode === "native") { ctx.ui.setFooter(undefined); return; }
|
|
26
|
+
ctx.ui.setFooter((tui, theme, data) => {
|
|
27
|
+
const monitor = config.branch ? watchGit(ctx.sessionManager.getCwd(), () => tui.requestRender()) : undefined;
|
|
28
|
+
activeGit = monitor;
|
|
29
|
+
const unsubscribe = data.onBranchChange(() => { monitor?.refresh(); tui.requestRender(); });
|
|
30
|
+
return {
|
|
31
|
+
dispose() { unsubscribe(); monitor?.dispose(); if (activeGit === monitor) activeGit = undefined; },
|
|
32
|
+
invalidate() {},
|
|
33
|
+
render(width: number): string[] {
|
|
34
|
+
const state = monitor?.value ?? { kind: "none" as const };
|
|
35
|
+
const git = config.branch ? gitText(state, data.getGitBranch() ?? undefined) : "";
|
|
36
|
+
const gitSuffix = git ? ` (${git})` : "";
|
|
37
|
+
const name = config.session ? ctx.sessionManager.getSessionName() : undefined;
|
|
38
|
+
const suffix = `${gitSuffix}${name ? ` • ${name}` : ""}`;
|
|
39
|
+
const display = resolveDisplayPath(ctx.sessionManager.getCwd(), homedir(), config.aliases);
|
|
40
|
+
const lines = [directoryLine(display.path, suffix, width, {
|
|
41
|
+
mode: config.mode === "native" ? "short" : config.mode,
|
|
42
|
+
icon: config.icon,
|
|
43
|
+
aliasName: display.aliasName,
|
|
44
|
+
style: {
|
|
45
|
+
normal: (text) => theme.fg("dim", text),
|
|
46
|
+
alias: (text) => theme.fg("mdLink", text),
|
|
47
|
+
suffix: (text) => theme.fg(gitColor(state), text.slice(0, gitSuffix.length)) + theme.fg("dim", text.slice(gitSuffix.length)),
|
|
48
|
+
},
|
|
49
|
+
})];
|
|
50
|
+
|
|
51
|
+
const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
52
|
+
let hitRate: number | undefined;
|
|
53
|
+
// Include usage before compaction and usage from tools and summaries.
|
|
54
|
+
for (const entry of ctx.sessionManager.getEntries()) {
|
|
55
|
+
const usage = entry.type === "message"
|
|
56
|
+
? (entry.message.role === "assistant" || entry.message.role === "toolResult" ? entry.message.usage : undefined)
|
|
57
|
+
: (entry.type === "usage" || entry.type === "compaction" || entry.type === "branch_summary" ? entry.usage : undefined);
|
|
58
|
+
if (!usage) continue;
|
|
59
|
+
totals.input += usage.input ?? 0;
|
|
60
|
+
totals.output += usage.output ?? 0;
|
|
61
|
+
totals.cacheRead += usage.cacheRead ?? 0;
|
|
62
|
+
totals.cacheWrite += usage.cacheWrite ?? 0;
|
|
63
|
+
totals.cost += usage.cost?.total ?? 0;
|
|
64
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
65
|
+
const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
66
|
+
hitRate = prompt > 0 ? usage.cacheRead / prompt * 100 : undefined;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const stats: string[] = [];
|
|
70
|
+
for (const [key, prefix] of [["input", "↑"], ["output", "↓"], ["cacheRead", "R"], ["cacheWrite", "W"]] as const) {
|
|
71
|
+
if (totals[key]) stats.push(`${prefix}${tokens(totals[key])}`);
|
|
72
|
+
}
|
|
73
|
+
if ((totals.cacheRead || totals.cacheWrite) && hitRate !== undefined) stats.push(`CH${hitRate.toFixed(1)}%`);
|
|
74
|
+
const model = ctx.model;
|
|
75
|
+
const subscription = model && (model.provider === "kimi-coding" || ctx.modelRegistry.isUsingOAuth(model));
|
|
76
|
+
if (totals.cost || subscription) stats.push(`$${totals.cost.toFixed(3)}${subscription ? " (sub)" : ""}`);
|
|
77
|
+
const usage = ctx.getContextUsage();
|
|
78
|
+
const percent = usage?.percent;
|
|
79
|
+
const context = `${percent == null ? "?" : percent.toFixed(1) + "%"}/${tokens(usage?.contextWindow ?? model?.contextWindow ?? 0)}`;
|
|
80
|
+
stats.push(percent != null && percent > 70 ? theme.fg(percent > 90 ? "error" : "warning", context) : context);
|
|
81
|
+
const left = truncateToWidth(stats.join(" "), width, "…");
|
|
82
|
+
let right = model?.id ?? "no-model";
|
|
83
|
+
if (model?.reasoning) right += ` • ${pi.getThinkingLevel()}`;
|
|
84
|
+
if (model && data.getAvailableProviderCount() > 1) {
|
|
85
|
+
const provider = `(${model.provider}) ${right}`;
|
|
86
|
+
if (visibleWidth(left) + 2 + visibleWidth(provider) <= width) right = provider;
|
|
87
|
+
}
|
|
88
|
+
const available = width - visibleWidth(left) - 2;
|
|
89
|
+
right = available > 0 ? truncateToWidth(right, available, "…") : "";
|
|
90
|
+
const padding = right ? " ".repeat(Math.max(2, width - visibleWidth(left) - visibleWidth(right))) : "";
|
|
91
|
+
lines.push(theme.fg("dim", left) + theme.fg("dim", padding + right));
|
|
92
|
+
const statuses = [...data.getExtensionStatuses()].sort(([a], [b]) => a.localeCompare(b));
|
|
93
|
+
if (statuses.length) {
|
|
94
|
+
const text = statuses.map(([, value]) => value.replace(/[\r\n\t]/g, " ")).join(" ");
|
|
95
|
+
lines.push(truncateToWidth(text, width, "…"));
|
|
96
|
+
}
|
|
97
|
+
return lines;
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
});
|
|
101
|
+
};
|
|
102
|
+
pi.on("session_start", async (_event, ctx) => { load(ctx); install(ctx); });
|
|
103
|
+
pi.on("tool_result", () => { activeGit?.refresh(); });
|
|
104
|
+
pi.on("agent_end", () => { activeGit?.refresh(); });
|
|
105
|
+
pi.on("session_shutdown", () => { activeGit?.dispose(); activeGit = undefined; });
|
|
106
|
+
pi.registerCommand("path-bar", {
|
|
107
|
+
description: "Configure the path bar and manage folder aliases",
|
|
108
|
+
handler: async (_args, ctx) => {
|
|
109
|
+
if (ctx.mode !== "tui") { ctx.ui.notify("/path-bar requires TUI mode", "error"); return; }
|
|
110
|
+
load(ctx);
|
|
111
|
+
install(ctx);
|
|
112
|
+
const save = (change: (next: Config) => void) => {
|
|
113
|
+
try { config = store.update(change); install(ctx); return true; }
|
|
114
|
+
catch (error) { ctx.ui.notify(`Could not save: ${error instanceof Error ? error.message : String(error)}`, "error"); return false; }
|
|
115
|
+
};
|
|
116
|
+
await openSettings(ctx, () => config, save);
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
}
|
package/src/path.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
2
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
3
|
+
import type { FolderAlias, PathMode } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
export interface PathOptions {
|
|
6
|
+
mode?: Exclude<PathMode, "native">;
|
|
7
|
+
icon?: boolean;
|
|
8
|
+
aliasName?: string;
|
|
9
|
+
style?: { normal: (text: string) => string; alias: (text: string) => string; suffix?: (text: string) => string };
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const clean = (text: string) => text.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
|
|
13
|
+
const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
14
|
+
const initial = (text: string) => segmenter.segment(text)[Symbol.iterator]().next().value?.segment ?? "";
|
|
15
|
+
|
|
16
|
+
export function homePath(cwd: string, home: string): string {
|
|
17
|
+
const tail = relative(resolve(home), resolve(cwd));
|
|
18
|
+
if (tail === "") return "~";
|
|
19
|
+
if (tail !== ".." && !tail.startsWith(`..${sep}`) && !isAbsolute(tail)) return `~/${tail.split(sep).join("/")}`;
|
|
20
|
+
return cwd;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function resolveDisplayPath(cwd: string, home: string, aliases: FolderAlias[]): { path: string; aliasName?: string } {
|
|
24
|
+
const matches = aliases.map((alias) => ({ alias, tail: relative(resolve(alias.path), resolve(cwd)) }))
|
|
25
|
+
.filter(({ tail }) => tail !== ".." && !tail.startsWith(`..${sep}`) && !isAbsolute(tail))
|
|
26
|
+
.sort((a, b) => b.alias.path.length - a.alias.path.length);
|
|
27
|
+
const match = matches[0];
|
|
28
|
+
return match
|
|
29
|
+
? { path: match.alias.name + (match.tail ? `/${match.tail.split(sep).join("/")}` : ""), aliasName: match.alias.name }
|
|
30
|
+
: { path: homePath(cwd, home) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function displayPath(cwd: string, home: string, aliases: FolderAlias[]): string {
|
|
34
|
+
return resolveDisplayPath(cwd, home, aliases).path;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Relative and named roots (including ~) have an icon; absolute roots do not. */
|
|
38
|
+
export function formatPath(path: string, width: number, options: PathOptions = {}): string {
|
|
39
|
+
if (width <= 0) return "";
|
|
40
|
+
path = clean(path);
|
|
41
|
+
const absolute = isAbsolute(path);
|
|
42
|
+
const icon = absolute || options.icon === false ? "" : "\uf07c ";
|
|
43
|
+
const paint = (text: string, hasRoot = true) => {
|
|
44
|
+
if (!options.style) return text;
|
|
45
|
+
const { normal, alias } = options.style;
|
|
46
|
+
const name = options.aliasName;
|
|
47
|
+
if (!hasRoot || !name || (path !== name && !path.startsWith(name + "/"))) return normal(text);
|
|
48
|
+
const start = icon.length;
|
|
49
|
+
return normal(text.slice(0, start)) + alias(text.slice(start, start + name.length)) + normal(text.slice(start + name.length));
|
|
50
|
+
};
|
|
51
|
+
const full = icon + path;
|
|
52
|
+
if (options.mode === "full") return truncateToWidth(paint(full), width, "…");
|
|
53
|
+
if (options.mode === "auto" && visibleWidth(full) <= width) return paint(full);
|
|
54
|
+
const parts = path.split("/").filter(Boolean);
|
|
55
|
+
if (parts.length < 2) return truncateToWidth(paint(full), width, "…");
|
|
56
|
+
const root = absolute ? "/" : parts.shift()! + "/";
|
|
57
|
+
const leaf = parts.pop()!;
|
|
58
|
+
const shortened = icon + root + [...parts.map(initial), leaf].join("/");
|
|
59
|
+
if (visibleWidth(shortened) <= width) return paint(shortened);
|
|
60
|
+
const collapsed = icon + root + (parts.length ? "…/" : "") + leaf;
|
|
61
|
+
if (visibleWidth(collapsed) <= width) return paint(collapsed);
|
|
62
|
+
// At very small widths preserve the directory name before the root or icon.
|
|
63
|
+
if (visibleWidth(leaf) <= width) return paint(leaf, false);
|
|
64
|
+
return truncateToWidth(paint(leaf, false), width, "…");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function directoryLine(path: string, suffix: string, width: number, options: PathOptions = {}): string {
|
|
68
|
+
if (width <= 0) return "";
|
|
69
|
+
suffix = clean(suffix);
|
|
70
|
+
// Reserve at least half of the line for the path. Trim branch/session first.
|
|
71
|
+
const tail = truncateToWidth(suffix, Math.floor(width / 2), "…");
|
|
72
|
+
const styledTail = options.style?.suffix
|
|
73
|
+
? truncateToWidth(options.style.suffix(suffix), Math.floor(width / 2), "…")
|
|
74
|
+
: options.style ? options.style.normal(tail) : tail;
|
|
75
|
+
return truncateToWidth(formatPath(path, width - visibleWidth(tail), options) + styledTail, width, "…");
|
|
76
|
+
}
|
package/src/settings.ts
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { getSettingsListTheme } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { Container, SettingsList, Text, type SettingItem } from "@earendil-works/pi-tui";
|
|
4
|
+
import { aliasName, folderPath, setAlias, type Config, type FolderAlias, type PathMode } from "./config.ts";
|
|
5
|
+
|
|
6
|
+
type Save = (change: (config: Config) => void) => boolean;
|
|
7
|
+
const modes: Record<PathMode, string> = { short: "Short", auto: "Auto", full: "Full", native: "Native footer" };
|
|
8
|
+
const switches = ["On", "Off"];
|
|
9
|
+
|
|
10
|
+
async function editAlias(ctx: ExtensionContext, save: Save, previous?: FolderAlias) {
|
|
11
|
+
const pathInput = await ctx.ui.input(previous ? "Folder path (leave blank to keep the current value)" : "Folder path (blank: current directory; or enter an absolute or ~/ path)", previous?.path ?? ctx.sessionManager.getCwd());
|
|
12
|
+
if (pathInput === undefined) return;
|
|
13
|
+
const path = folderPath(pathInput.trim() ? pathInput : previous?.path ?? ctx.sessionManager.getCwd());
|
|
14
|
+
const nameInput = await ctx.ui.input(previous ? "Alias name (leave blank to keep the current value)" : "Alias name", previous?.name ?? "e.g. Projects");
|
|
15
|
+
if (nameInput === undefined) return;
|
|
16
|
+
const name = aliasName(previous && !nameInput.trim() ? previous.name : nameInput);
|
|
17
|
+
if (save((config) => setAlias(config, { path, name }, previous?.path))) ctx.ui.notify("Folder alias saved", "info");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function openSettings(ctx: ExtensionContext, get: () => Config, save: Save) {
|
|
21
|
+
let selected = "mode";
|
|
22
|
+
while (true) {
|
|
23
|
+
const action = await ctx.ui.custom<string | undefined>((tui, theme, _kb, done) => {
|
|
24
|
+
const config = get();
|
|
25
|
+
const items: SettingItem[] = [
|
|
26
|
+
{ id: "mode", label: "Path display", currentValue: modes[config.mode], values: Object.values(modes), description: "Short: always abbreviate. Auto: abbreviate when needed. Full: never abbreviate." },
|
|
27
|
+
...([ ["icon", "Folder icon"], ["branch", "Git status"], ["session", "Session name"] ] as const).map(([id, label]) => ({ id, label, currentValue: config[id] ? "On" : "Off", values: switches })),
|
|
28
|
+
{ id: "add", label: "Add folder alias", currentValue: "Open", values: ["Open"], description: "Name any folder. A blank path uses the current directory. Only the display changes." },
|
|
29
|
+
{ id: "manage", label: "Manage folder aliases", currentValue: `${config.aliases.length} aliases`, values: ["Open"], description: "Edit a path or name, or delete an alias." },
|
|
30
|
+
];
|
|
31
|
+
const list = new SettingsList(items, 10, getSettingsListTheme(), (id, value) => {
|
|
32
|
+
selected = id;
|
|
33
|
+
if (id === "add" || id === "manage") { done(id); return; }
|
|
34
|
+
const previous = id === "mode" ? modes[get().mode] : get()[id as "icon" | "branch" | "session"] ? "On" : "Off";
|
|
35
|
+
const success = save((next) => {
|
|
36
|
+
if (id === "mode") next.mode = (Object.keys(modes) as PathMode[]).find((mode) => modes[mode] === value)!;
|
|
37
|
+
else next[id as "icon" | "branch" | "session"] = value === "On";
|
|
38
|
+
});
|
|
39
|
+
if (!success) list.updateValue(id, previous);
|
|
40
|
+
tui.requestRender();
|
|
41
|
+
}, () => done(undefined));
|
|
42
|
+
list.selectItem(selected);
|
|
43
|
+
const container = new Container();
|
|
44
|
+
container.addChild(new Text(theme.fg("accent", theme.bold("Path bar settings")), 0, 1));
|
|
45
|
+
container.addChild(list);
|
|
46
|
+
return {
|
|
47
|
+
render: (width: number) => container.render(width),
|
|
48
|
+
invalidate: () => container.invalidate(),
|
|
49
|
+
handleInput: (input: string) => { list.handleInput(input); tui.requestRender(); },
|
|
50
|
+
};
|
|
51
|
+
});
|
|
52
|
+
if (!action) return;
|
|
53
|
+
try {
|
|
54
|
+
if (action === "add") { await editAlias(ctx, save); continue; }
|
|
55
|
+
const aliases = get().aliases;
|
|
56
|
+
if (!aliases.length) { ctx.ui.notify("No folder aliases yet. Add one first.", "info"); continue; }
|
|
57
|
+
const labels = aliases.map((alias) => `${alias.name} → ${alias.path}`);
|
|
58
|
+
const choice = await ctx.ui.select("Select a folder alias", labels);
|
|
59
|
+
if (choice === undefined) continue;
|
|
60
|
+
const alias = aliases[labels.indexOf(choice)];
|
|
61
|
+
if (!alias) continue;
|
|
62
|
+
const operation = await ctx.ui.select(`${alias.name} → ${alias.path}`, ["Edit path or name", "Delete alias"]);
|
|
63
|
+
if (operation === "Edit path or name") await editAlias(ctx, save, alias);
|
|
64
|
+
if (operation === "Delete alias" && await ctx.ui.confirm("Delete folder alias", `Delete "${alias.name}"? The actual folder will not be deleted.`)) {
|
|
65
|
+
if (save((config) => { config.aliases = config.aliases.filter((item) => item.path !== alias.path); })) ctx.ui.notify("Folder alias deleted", "info");
|
|
66
|
+
}
|
|
67
|
+
} catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"); }
|
|
68
|
+
}
|
|
69
|
+
}
|