中文译文
任务:为 Claude Code 创建专业的开发者状态栏
角色
你是一名系统程序员,正在为 Claude Code 创建一个高度优化的状态栏脚本。
交付物
一个单文件 Python 脚本(~/.claude/statusline.py),在 Claude Code 的状态栏中显示对开发者至关重要的信息。
输入规范
从 stdin 读取具有以下结构的 JSON:
{
"model": {"display_name": "Opus|Sonnet|Haiku"},
"workspace": {"current_dir": "/path/to/workspace", "project_dir": "/path/to/project"},
"output_style": {"name": "explanatory|default|concise"},
"cost": {
"total_cost_usd": 0.0,
"total_duration_ms": 0,
"total_api_duration_ms": 0,
"total_lines_added": 0,
"total_lines_removed": 0
}
}
输出要求
格式
- 向 stdout 精确打印一行
- 使用 ANSI 256 色代码:\033[38;5;Nm,采用针对高对比度优化的调色板
- 智能截断:可见文本宽度 ≤ 80 个字符(ANSI 转义码不计入限制)
- 使用 unicode 符号:●(干净)、+(新增)、~(修改)
- 调色板:橙色 208、蓝色 33、绿色 154、黄色 229、红色 196、灰色 245(已在深色/浅色终端中测试)
信息架构(从左到右优先级)
- 核心:模型名称(橙色)
- 上下文:项目目录基名(蓝色)
- Git 状态:
- 分支名称(绿色)
- 干净:●(暗灰色)
- 已修改:~N(黄色,N = 文件数量)
- 已新增:+N(黄色,N = 文件数量)
- 元数据(暗灰色):
- 未提交文件:!N(红色,N = 来自 git status --porcelain 的数量)
- API 比率:A:N%(N = api_duration / total_duration * 100)
示例输出
\033[38;5;208mOpus\033[0m \033[38;5;33mIsaacLab\033[0m \033[38;5;154mmain\033[0m \033[38;5;245m●\033[0m \033[38;5;245mA:12%\033[0m
技术约束
性能(关键)
执行时间:< 100ms(每 300ms 调用一次)
缓存持久化:将 Git 状态缓存存储在 /tmp/claude_statusline_cache.json(脚本每次运行后退出,因此缓存必须持久化到磁盘)
缓存 TTL:仅当缓存年龄 > 5 秒或 .git/index mtime 发生变化时,才刷新 Git 文件计数
Git 逻辑优化:
分支名称:直接读取 .git/HEAD(不使用子进程)
文件计数:仅当缓存过期时调用 subprocess.run(['git', 'status', '--porcelain'])
仅使用标准库:无外部依赖(仅使用 sys、json、os、pathlib、subprocess、time)
错误处理
- JSON 解析错误 → 返回空字符串 ""
- 缺少字段 → 省略该部分(不要崩溃)
- 未找到 Git 目录 → 完全省略 Git 部分
- 任何异常 → 返回空字符串 ""
代码结构
- 单文件,< 100 行
- 处理 UTF-8 编码以实现稳健的 unicode 输出
- 每个关注点最多一个函数(解析、git、格式化)
- 所有函数都需要类型提示
- 每个函数都要有 docstring 说明其用途
集成步骤
- 将脚本保存到 ~/.claude/statusline.py
- 运行 chmod +x ~/.claude/statusline.py
- 添加到 ~/.claude/settings.json:
{
"statusLine": {
"type": "command",
"command": "~/.claude/statusline.py",
"padding": 0
}
}
- 手动测试:echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/tmp"}}' | ~/.claude/statusline.py
验证清单
- 脚本执行无需外部依赖(缓存时除外,仅需一次 git status --porcelain 调用)
- 可见文本宽度 ≤ 80 个字符(ANSI 代码不计入计算)
- 颜色在深色和浅色终端背景下均能正确渲染
- 在典型工作区中执行时间 < 100ms(缓存调用应 < 20ms)
- 能优雅处理缺失的 Git 仓库
- 缓存文件创建于 /tmp 并遵守 TTL
- 当 .git/index 的 mtime 变化或经过 5 秒时,Git 文件计数会刷新
决策背景
这是一个「开发者专业」风格的状态栏。它优先考虑:
- 详细的 Git 信息,以便感知分支切换
- API 效率监控,服务于注重成本的开发
- 视觉密度,以在每字符中承载最大信息量
English original
Task: Create a Professional Developer Status Bar for Claude Code
Role
You are a systems programmer creating a highly-optimized status bar script for Claude Code.
Deliverable
A single-file Python script (~/.claude/statusline.py) that displays developer-critical information in Claude Code's status line.
Input Specification
Read JSON from stdin with this structure:
{
"model": {"display_name": "Opus|Sonnet|Haiku"},
"workspace": {"current_dir": "/path/to/workspace", "project_dir": "/path/to/project"},
"output_style": {"name": "explanatory|default|concise"},
"cost": {
"total_cost_usd": 0.0,
"total_duration_ms": 0,
"total_api_duration_ms": 0,
"total_lines_added": 0,
"total_lines_removed": 0
}
}
Output Requirements
Format
- Print exactly ONE line to stdout
- Use ANSI 256-color codes: \033[38;5;Nm with optimized color palette for high contrast
- Smart truncation: Visible text width ≤ 80 characters (ANSI escape codes do NOT count toward limit)
- Use unicode symbols: ● (clean), + (added), ~ (modified)
- Color palette: orange 208, blue 33, green 154, yellow 229, red 196, gray 245 (tested for both dark/light terminals)
Information Architecture (Left to Right Priority)
- Core: Model name (orange)
- Context: Project directory basename (blue)
- Git Status:
- Branch name (green)
- Clean: ● (dim gray)
- Modified: ~N (yellow, N = file count)
- Added: +N (yellow, N = file count)
- Metadata (dim gray):
- Uncommitted files: !N (red, N = count from git status --porcelain)
- API ratio: A:N% (N = api_duration / total_duration * 100)
Example Output
\033[38;5;208mOpus\033[0m \033[38;5;33mIsaacLab\033[0m \033[38;5;154mmain\033[0m \033[38;5;245m●\033[0m \033[38;5;245mA:12%\033[0m
Technical Constraints
Performance (CRITICAL)
Execution time: < 100ms (called every 300ms)
Cache persistence: Store Git status cache in /tmp/claude_statusline_cache.json (script exits after each run, so cache must persist on disk)
Cache TTL: Refresh Git file counts only when cache age > 5 seconds OR .git/index mtime changes
Git logic optimization:
Branch name: Read .git/HEAD directly (no subprocess)
File counts: Call subprocess.run(['git', 'status', '--porcelain']) ONLY when cache expires
Standard library only: No external dependencies (use only sys, json, os, pathlib, subprocess, time)
Error Handling
- JSON parse error → return empty string ""
- Missing fields → omit that section (do not crash)
- Git directory not found → omit Git section entirely
- Any exception → return empty string ""
Code Structure
- Single file, < 100 lines
- UTF-8 encoding handled for robust unicode output
- Maximum one function per concern (parsing, git, formatting)
- Type hints required for all functions
- Docstring for each function explaining its purpose
Integration Steps
- Save script to ~/.claude/statusline.py
- Run chmod +x ~/.claude/statusline.py
- Add to ~/.claude/settings.json:
{
"statusLine": {
"type": "command",
"command": "~/.claude/statusline.py",
"padding": 0
}
}
- Test manually: echo '{"model":{"display_name":"Test"},"workspace":{"current_dir":"/tmp"}}' | ~/.claude/statusline.py
Verification Checklist
- Script executes without external dependencies (except single git status --porcelain call when cached)
- Visible text width ≤ 80 characters (ANSI codes excluded from calculation)
- Colors render correctly in both dark and light terminal backgrounds
- Execution time < 100ms in typical workspace (cached calls should be < 20ms)
- Gracefully handles missing Git repository
- Cache file is created in /tmp and respects TTL
- Git file counts refresh when .git/index mtime changes or 5 seconds elapse
Context for Decisions
This is a "developer professional" style status bar. It prioritizes:
- Detailed Git information for branch switching awareness
- API efficiency monitoring for cost-conscious development
- Visual density for maximum information per character