Skip to content
Back to search

claude-statusbar

SkillWorks with Claude CodeGitHubIncomplete

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/leeguooooo--claude-code-usage-bar/badge.svg)](/listings/leeguooooo--claude-code-usage-bar)

HTML

<a href="/listings/leeguooooo--claude-code-usage-bar"><img src="/api/listings/leeguooooo--claude-code-usage-bar/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.sh | bash

A prebuilt binary for macOS Apple Silicon and Linux x86_64 — no Python needed. Other platforms fall back to pip.

**Windows** (PowerShell, no admin):

irm https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.ps1 | iex

**pip / uv:**

pip install claude-statusbar     # or: uv tool install / pipx install
cs --setup                       # wires the statusLine hook + installs the skill

Restart Claude Code and the bar appears. `cs` upgrades itself every 6 hours; if you're stuck on an old version, run `cs upgrade` or re-run the one-liner ([why](docs/troubleshooting.md#stuck-on-an-old-version)). More paths in the **[install guide](docs/install.md)**.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 31 lines
  1. {
  2. "name": "claude-statusbar",
  3. "owner": {
  4. "name": "leeguooooo",
  5. "email": "leeguooooo@gmail.com"
  6. },
  7. "metadata": {
  8. "description": "Self-hosted marketplace for the claude-statusbar plugin. Add with `/plugin marketplace add leeguooooo/claude-code-usage-bar`, then `/plugin install claude-statusbar`. The plugin wires Claude Code statusLine + slash commands; the render engine is the `cs` CLI.",
  9. "version": "3.53.1"
  10. },
  11. "plugins": [
  12. {
  13. "name": "claude-statusbar",
  14. "source": "./",
  15. "description": "Lightweight Claude Code status-line monitor: 5h/7d rate-limit usage, reset timers, projection/forecast, model + context, prompt-cache countdown, optional cost/balance, project/branch/session/activity lines. 3 styles x 9 themes. Install the `cs` CLI with the GitHub Release installer.",
  16. "category": "monitoring",
  17. "tags": [
  18. "statusline",
  19. "monitoring",
  20. "rate-limit",
  21. "usage",
  22. "projection",
  23. "forecast",
  24. "context-window",
  25. "prompt-cache",
  26. "todos",
  27. "subscriber"
  28. ]
  29. }
  30. ]
  31. }
README.md · README · 129 lines · 2 findings marked
  1. > Using **Codex CLI**? Try the sibling project **[Codex Statebar](https://github.com/leeguooooo/codex-statebar)** — the same status bar, built for Codex.
  2. <div align="center">
  3. # Claude Status Bar
  4. **Your Claude Code usage, at a glance.**
  5. 5h / 7d rate-limit bars, reset countdowns, model, context window, and prompt-cache
  6. freshness — inline in Claude Code's status line.
  7. [![PyPI](https://img.shields.io/pypi/v/claude-statusbar.svg?color=2b7)](https://pypi.org/project/claude-statusbar/)
  8. [![Downloads](https://static.pepy.tech/badge/claude-statusbar/month)](https://pepy.tech/project/claude-statusbar)
  9. [![Python](https://img.shields.io/pypi/pyversions/claude-statusbar.svg)](https://pypi.org/project/claude-statusbar/)
  10. [![CI](https://github.com/leeguooooo/claude-code-usage-bar/actions/workflows/ci.yml/badge.svg)](https://github.com/leeguooooo/claude-code-usage-bar/actions/workflows/ci.yml)
  11. [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
  12. [![GitHub stars](https://img.shields.io/github/stars/leeguooooo/claude-code-usage-bar?style=social)](https://github.com/leeguooooo/claude-code-usage-bar/stargazers)
  13. **English** · [简体中文](README.zh-CN.md) · [Install](docs/install.md) · [Documentation](#documentation)
  14. ![Aurora — the default look](https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/docs/images/look-aurora.png)
  15. </div>
  16. Claude Code tells you almost nothing about where you stand against your rate limits.
  17. `cs` puts the numbers that matter on one quiet line at the bottom of your terminal:
  18. how much you have left, and when it resets.
  19. | Line | Segments |
  20. |---|---|
  21. | **Usage** | 5h / 7d rate-limit bars, reset countdowns, end-of-window projections (`→NN%`), model & context window, prompt-cache countdown, optional session cost or relay balance |
  22. | **Project** | git worktree marker (`name (🌳3)` / `worktree (🌳3)`), project name, branch, session `+/−` lines, duration, version |
  23. - **Official numbers** — the same 5h / 7d limits Claude Code enforces, not a local guess.
  24. - **Prompt-cache countdown** — `❄ 4m23s` tells you when the next turn pays full price.
  25. - **Fast** — native cache reader plus a background daemon; well under 1% CPU at one refresh per second.
  26. - **Opt-in extras** — cost, relay balance, git ahead/behind, activity, IP checks, [IELTS writing-coach](https://github.com/leeguooooo/prompt-language-coach) progress.
  27. ## Install
  28. ```bash
  29. curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 41 on GitHub
  30. ```
  31. A prebuilt binary for macOS Apple Silicon and Linux x86_64 — no Python needed. Other platforms fall back to pip.
  32. **Windows** (PowerShell, no admin):
  33. ```powershell
  34. irm https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.ps1 | iex
  35. ```
  36. **pip / uv:**
  37. ```bash
  38. pip install claude-statusbar # or: uv tool install / pipx install
  39. cs --setup # wires the statusLine hook + installs the skill
  40. ```
  41. Restart Claude Code and the bar appears. `cs` upgrades itself every 6 hours; if you're stuck on
  42. an old version, run `cs upgrade` or re-run the one-liner
  43. ([why](docs/troubleshooting.md#stuck-on-an-old-version)). More paths in the **[install guide](docs/install.md)**.
  44. ## Customize
  45. Three looks — aurora with block bars (default), aurora with a thin line, and classic:
  46. ![aurora, block bars (default)](https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/docs/images/look-aurora.png)
  47. ![aurora, thin line](https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/docs/images/look-thin.png)
  48. ![classic](https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/docs/images/look-classic.png)
  49. `cs theme` picks one with a live preview:
  50. ![cs theme — pick a look with a live preview](https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/docs/images/picker.gif)
  51. ```bash
  52. cs theme # pick one with a live preview (↑/↓, Enter)
  53. cs config set bar_glyph thin # thin ━ line instead of ■ blocks (default)
  54. cs config set style classic # the original battery-bar look
  55. cs config set narrow_layout stack # stack quota bars in narrow panes
  56. cs preview # all three looks, with your real numbers
  57. cs config show # every key, and which ones you changed
  58. ```
  59. ## Documentation
  60. | Guide | What's inside |
  61. |-------|---------------|
  62. | [Install](docs/install.md) | Binary, PyPI, skill-only, plugin, Codex bridge |
  63. | [What it shows](docs/segments.md) | Every segment, icon and color threshold |
  64. | [Looks](docs/styles-and-themes.md) | The three looks, slash commands |
  65. | [Configuration](docs/configuration.md) | All keys, env vars, JSON output |
  66. | [Fast mode (daemon)](docs/daemon.md) | Daemon, auto-start, refresh and caching |
  67. | [No-quota mode](docs/no-quota-mode.md) | Relay / Bedrock / Vertex layout and balance |
  68. | [Cache countdown](docs/cache-countdown.md) | How `❄ 4m23s` is computed |
  69. | [Troubleshooting](docs/troubleshooting.md) | `cs doctor`, IP checks, upgrading |
  70. Want charts and weekly cost breakdowns instead of one line? Run
  71. [ccusage](https://github.com/ryoppippi/ccusage) or
  72. [Claude Code Usage Monitor](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor) in a
  73. side pane — they coexist with `cs`.
  74. **[ccx](https://github.com/aaronwong1999/ccx)** — keeps a Claude Code session and a Codex thread
  75. linked on macOS. With the bar installed, ccx's menu bar app warns you when Claude's 5-hour
  76. window passes 90% or its weekly quota is exhausted, and offers to continue the newest session in Codex in one click (no
  77. config; ccx reads `rate_limits` from `~/.cache/claude-statusbar/last_stdin.json` while it's fresh).
  78. ## Contributing
  79. PRs welcome — see **[CONTRIBUTING.md](CONTRIBUTING.md)** (setup, tests, architecture, release flow)
  80. and **[SECURITY.md](SECURITY.md)**. Changes per version: **[CHANGELOG.md](CHANGELOG.md)**.
  81. ## Acknowledgments
  82. - [@marcwimmer](https://github.com/marcwimmer) — original `show_cache_age` widget ([#9](https://github.com/leeguooooo/claude-code-usage-bar/pull/9))
  83. - [claude-monitor](https://github.com/Maciek-roboblog/Claude-Code-Usage-Monitor) — token-usage analysis library used as the optional fast-path data source
  84. <a href="https://github.com/leeguooooo/claude-code-usage-bar/graphs/contributors">
  85. <img src="https://contrib.rocks/image?repo=leeguooooo/claude-code-usage-bar" alt="Contributors" />
  86. </a>
  87. ---
  88. <div align="center">
  89. <sub>MIT © <a href="https://github.com/leeguooooo">leeguooooo</a> · Built for people who live in Claude Code.</sub>
  90. </div>
  91. ## Author
  92. Built by **郭立 (Guo Li / leeguoo)** — [leeguoo.com](https://leeguoo.com/about) · [GitHub](https://github.com/leeguooooo) · [X](https://x.com/leeguooooo) · more tools in the [*-use family](https://github.com/leeguooooo/plugins).
demo/record_demo.sh · Bundled script · 40 lines · 1 finding marked
  1. #!/bin/bash
  2. # Demo script for recording installation and usage of claude-statusbar
  3. # Requires: asciinema (brew install asciinema) and asciicast2gif or svg-term-cli
  4. echo "📹 Claude Status Bar Demo Recording Script"
  5. echo "========================================="
  6. echo ""
  7. echo "This script will help you record a demo of the installation process."
  8. echo "Prerequisites: asciinema (brew install asciinema)"
  9. echo ""
  10. # Colors for output
  11. GREEN='\033[0;32m'
  12. BLUE='\033[0;34m'
  13. NC='\033[0m' # No Color
  14. # Start recording
  15. echo -e "${BLUE}Starting recording...${NC}"
  16. echo "Press Ctrl+D when done recording"
  17. echo ""
  18. asciinema rec --title="Claude Status Bar Installation Demo" demo.cast
  19. echo ""
  20. echo -e "${GREEN}Recording saved to demo.cast${NC}"
  21. echo ""
  22. echo "To convert to GIF, you can use:"
  23. echo "1. Upload to asciinema.org and use their embed"
  24. echo "2. Use svg-term-cli: npx svg-term-cli --cast demo.cast --out demo.svg"
  25. echo "3. Use asciicast2gif: docker run --rm -v \$PWD:/data asciinema/asciicast2gif demo.cast demo.gif"
  26. echo ""
  27. echo "Demo script outline:"
  28. echo "==================="
  29. echo "1. Show current directory: pwd"
  30. echo "2. Show we don't have claude-statusbar: which claude-statusbar (should fail)"
  31. echo "3. Run installation: curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/web-install.sh | bash"
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 37 on GitHub
  32. echo "4. Show it's installed: which claude-statusbar"
  33. echo "5. Run it: claude-statusbar"
  34. echo "6. Show the alias: cs"
install.ps1 · Bundled script · 40 lines · 2 findings marked
  1. # Windows installer for claude-statusbar (the `cs` status line for Claude Code).
  2. # irm https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.ps1 | iex
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 2 on GitHub
  3. # Needs uv (https://docs.astral.sh/uv/). If uv is missing it installs it with
  4. # winget (Microsoft's package manager, built into Windows 10/11) — it never runs
  5. # a remote install script; without winget it stops with install hints. Installs
  6. # the package as a uv tool (uv brings its own Python), puts the tool directory
  7. # on the user PATH, then runs `cs --setup`. Re-run to upgrade.
  8. # Wrapped in a script block so `irm | iex` doesn't leave settings in your shell.
    • Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
    • Line 8 on GitHub
  9. & {
  10. $ErrorActionPreference = 'Stop'
  11. if (-not (Get-Command uv -ErrorAction SilentlyContinue)) {
  12. if (Get-Command winget -ErrorAction SilentlyContinue) {
  13. Write-Host 'uv not found; installing it with winget...'
  14. winget install --id=astral-sh.uv -e --accept-source-agreements --accept-package-agreements
  15. # winget updates the persisted PATH, not this session's; reload it.
  16. $env:Path = @(
  17. [Environment]::GetEnvironmentVariable('Path', 'User'),
  18. [Environment]::GetEnvironmentVariable('Path', 'Machine'),
  19. "$env:LOCALAPPDATA\Microsoft\WinGet\Links",
  20. $env:Path
  21. ) -join ';'
  22. }
  23. if (-not (Get-Command uv -ErrorAction SilentlyContinue)) {
  24. Write-Host 'uv is required but could not be installed automatically. Install it, open a new terminal, then re-run:'
  25. Write-Host ' winget install --id=astral-sh.uv -e'
  26. Write-Host ' or see https://docs.astral.sh/uv/getting-started/installation/'
  27. throw 'uv not found'
  28. }
  29. }
  30. uv tool install --upgrade claude-statusbar
  31. if ($LASTEXITCODE) { throw 'uv tool install failed' }
  32. uv tool update-shell # adds the tool bin dir to the user PATH (new terminals)
  33. $env:Path = "$(uv tool dir --bin);$env:Path"
  34. cs --setup
  35. if ($LASTEXITCODE) { throw 'cs --setup failed' }
  36. Write-Host 'Done. Restart Claude Code to see the status bar.'
  37. }
install.sh · Bundled script · 437 lines · 2 findings marked
  1. #!/usr/bin/env bash
  2. # claude-statusbar — standalone binary installer (no Python, no pip required).
  3. #
  4. # Usage (read the script first, please):
  5. # curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.sh -o /tmp/cs.sh
  6. # less /tmp/cs.sh # audit it
  7. # bash /tmp/cs.sh
  8. #
  9. # Or, if you trust this repo:
  10. # curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 10 on GitHub
  11. #
  12. # What it does (full disclosure):
  13. # 1. Detects your OS + CPU arch and downloads the matching prebuilt `cs`
  14. # bundle from the latest GitHub Release (self-contained — no Python
  15. # needed on your machine). The installed bundle uses PyInstaller onedir,
  16. # not onefile, so the once-per-second status render never extracts `_MEI*`
  17. # runtime copies into your temp directory.
  18. # 2. Verifies the SHA-256 checksum published alongside it.
  19. # 3. Installs it to ~/.local/bin (no sudo; everything under $HOME) and, with
  20. # your [y/N] consent, adds ~/.local/bin to PATH in your shell rc.
  21. # 4. Runs `cs --setup` to wire the Claude Code statusLine + slash commands.
  22. # 5. Removes inactive `_MEI*` directories leaked by legacy onefile versions,
  23. # after stopping the old daemon and verifying no process has them open.
  24. #
  25. # If no prebuilt binary matches your platform (e.g. Linux arm64, Windows), it
  26. # automatically falls back to the pip/uv-based installer (web-install.sh),
  27. # which needs Python 3.9+.
  28. #
  29. # No sudo. No telemetry. The only remote hosts touched are github.com (release
  30. # assets) and, only on fallback, PyPI / astral.sh (uv).
  31. set -euo pipefail
  32. REPO="leeguooooo/claude-code-usage-bar"
  33. INSTALL_DIR="${CS_INSTALL_DIR:-$HOME/.local/bin}"
  34. BUNDLE_ROOT="${CS_BUNDLE_ROOT:-$HOME/.local/lib/claude-statusbar}"
  35. FALLBACK_URL="https://raw.githubusercontent.com/${REPO}/main/web-install.sh"
  36. # A pip/uv/pipx copy of claude-statusbar competes with this binary for the one
  37. # `cs` on PATH: whichever upgrades last rewrites the symlink and silently takes
  38. # over. We don't remove another package manager's package behind the user's
  39. # back, but staying quiet about it is how a stale uv 3.32.0 replaced a working
  40. # binary install without anyone noticing.
  41. warn_about_duplicate_installs() {
  42. local found=""
  43. [ -d "$HOME/.local/share/uv/tools/claude-statusbar" ] && found="uv tool"
  44. [ -d "$HOME/.local/pipx/venvs/claude-statusbar" ] && found="${found:+$found and }pipx"
  45. [ -n "$found" ] || return 0
  46. warn "Another claude-statusbar install ($found) is also present."
  47. echo " Both compete for $INSTALL_DIR/cs — whichever upgrades last wins."
  48. echo " Remove the other one so upgrades stay predictable:"
  49. [ -d "$HOME/.local/share/uv/tools/claude-statusbar" ] && \
  50. echo " uv tool uninstall claude-statusbar"
  51. [ -d "$HOME/.local/pipx/venvs/claude-statusbar" ] && \
  52. echo " pipx uninstall claude-statusbar"
  53. }
  54. # Scratch dir for the downloaded tarball, cleaned up on any exit. Declared here
  55. # (not inside the function that fills it) so the trap can still see it — see the
  56. # note at the mktemp call.
  57. TMP_DIR=""
  58. INSTALL_STAGE=""
  59. INSTALLED_BUNDLE_DIR=""
  60. DMG_MOUNT=""
  61. cleanup() {
  62. if [ -n "${DMG_MOUNT:-}" ]; then
  63. hdiutil detach "$DMG_MOUNT" -quiet || hdiutil detach "$DMG_MOUNT" -force -quiet || return 0
  64. fi
  65. [ -n "${TMP_DIR:-}" ] && rm -rf "$TMP_DIR"
  66. [ -n "${INSTALL_STAGE:-}" ] && rm -rf "$INSTALL_STAGE"
  67. return 0
  68. }
  69. trap cleanup EXIT
  70. GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; RED='\033[0;31m'; NC='\033[0m'
  71. say() { echo -e "${BLUE}$*${NC}"; }
  72. ok() { echo -e "${GREEN}$*${NC}"; }
  73. warn() { echo -e "${YELLOW}$*${NC}"; }
  74. err() { echo -e "${RED}$*${NC}" >&2; }
  75. echo -e "${BLUE}╔══════════════════════════════════════╗${NC}"
  76. echo -e "${BLUE}║ Claude Status Bar — binary install ║${NC}"
  77. echo -e "${BLUE}╚══════════════════════════════════════╝${NC}"
  78. echo ""
  79. # ---------------------------------------------------------------------------
  80. # ask_yes_no PROMPT — reads from /dev/tty so it works under `curl | bash`.
  81. # Returns 0 on yes; anything else (incl. no tty) is treated as "no".
  82. # ---------------------------------------------------------------------------
  83. ask_yes_no() {
  84. local reply
  85. if [ ! -r /dev/tty ]; then
  86. warn "(no /dev/tty — treating as 'no')"
  87. return 1
  88. fi
  89. printf "%s [y/N]: " "$1" > /dev/tty
  90. read -r reply < /dev/tty || return 1
  91. case "$reply" in y|Y|yes|YES) return 0 ;; *) return 1 ;; esac
  92. }
  93. # ---------------------------------------------------------------------------
  94. # fall_back_to_pip — hand off to the Python/pip installer for platforms with no
  95. # prebuilt binary. Runs it in-place via the same shell.
  96. # ---------------------------------------------------------------------------
  97. fall_back_to_pip() {
  98. warn "No prebuilt binary for this platform — falling back to the pip installer."
  99. warn "(needs Python 3.9+; it will use uv/pipx/pip, bootstrapping uv if needed)"
  100. if command -v curl >/dev/null 2>&1; then
  101. curl -fsSL "$FALLBACK_URL" | bash
  102. else
  103. err "curl not found; install Python + run: pip install claude-statusbar && cs --setup"
  104. exit 1
  105. fi
  106. exit $?
  107. }
  108. # ---------------------------------------------------------------------------
  109. # detect_asset — echo the release asset name for this OS/arch, or "" if none.
  110. # ---------------------------------------------------------------------------
  111. detect_asset() {
  112. local os arch
  113. case "$(uname -s)" in
  114. Darwin) os="darwin" ;;
  115. Linux) os="linux" ;;
  116. *) echo ""; return ;;
  117. esac
  118. case "$(uname -m)" in
  119. arm64|aarch64) arch="arm64" ;;
  120. x86_64|amd64) arch="x86_64" ;;
  121. *) echo ""; return ;;
  122. esac
  123. # Published matrix: darwin arm64, linux x86_64. Everything else (Intel mac,
  124. # linux arm64, Windows) has no prebuilt binary → fall back to pip.
  125. case "$os-$arch" in
  126. darwin-arm64|linux-x86_64) echo "cs-${os}-${arch}.tar.gz" ;;
  127. *) echo "" ;;
  128. esac
  129. }
  130. # ---------------------------------------------------------------------------
  131. # sha256_of FILE — portable SHA-256 (shasum on macOS, sha256sum on Linux).
  132. # ---------------------------------------------------------------------------
  133. sha256_of() {
  134. if command -v sha256sum >/dev/null 2>&1; then
  135. sha256sum "$1" | awk '{print $1}'
  136. else
  137. shasum -a 256 "$1" | awk '{print $1}'
  138. fi
  139. }
  140. verify_checksum() {
  141. local base="$1" asset="$2" directory="$3" want got
  142. if ! curl -fsSL "$base/$asset.sha256" -o "$directory/$asset.sha256"; then
  143. err "Checksum file unavailable for $asset; refusing to install."
  144. exit 1
  145. fi
  146. want="$(awk '{print $1}' "$directory/$asset.sha256")"
  147. got="$(sha256_of "$directory/$asset")"
  148. if [ "$want" != "$got" ]; then
  149. err "Checksum mismatch for $asset; refusing to install."
  150. exit 1
  151. fi
  152. ok "✓ Checksum verified"
  153. }
  154. verify_apple_signature() {
  155. local target="$1" info
  156. codesign --verify --strict "$target" || { err "Apple signature verification failed."; exit 1; }
  157. info="$(codesign --display --verbose=4 "$target" 2>&1)"
  158. if ! [[ "$info" == *"Authority=Developer ID Application:"* &&
  159. "$info" == *"TeamIdentifier=6ZPXG4KVVS"* ]]; then
  160. err "Unexpected developer identity; refusing to install."
  161. exit 1
  162. fi
  163. }
  164. # ---------------------------------------------------------------------------
  165. # stop_old_daemon — stop the legacy onefile daemon before replacing the
  166. # launcher. Its `_MEI*` directory can be hours old while still in active use,
  167. # so age alone is never a safe cleanup criterion.
  168. # ---------------------------------------------------------------------------
  169. stop_old_daemon() {
  170. if [ -x "$INSTALL_DIR/cs" ]; then
  171. "$INSTALL_DIR/cs" daemon stop >/dev/null 2>&1 || true
  172. # The HUD is another long-lived frozen process. Stop it before old
  173. # onedir versions are pruned; the installer restarts it below when the
  174. # Claude desktop app is present.
  175. "$INSTALL_DIR/cs" hud stop >/dev/null 2>&1 || true
  176. fi
  177. }
  178. # BSD mv follows a destination symlink to a directory unless `-h` is passed;
  179. # GNU mv uses `-T` for the same no-follow replacement semantics.
  180. replace_path_atomically() {
  181. local source="$1" target="$2"
  182. if [ "$(uname -s)" = "Darwin" ]; then
  183. mv -fh "$source" "$target"
  184. else
  185. mv -fT "$source" "$target"
  186. fi
  187. }
  188. # ---------------------------------------------------------------------------
  189. # install_onedir_bundle SOURCE_DIR — copy a release bundle into a content-
  190. # addressed version directory and atomically repoint ~/.local/bin/cs through a
  191. # stable `current` symlink. A failed copy can never leave a half-written CLI.
  192. # Sets INSTALLED_BUNDLE_DIR to the final bundle directory.
  193. # ---------------------------------------------------------------------------
  194. install_onedir_bundle() {
  195. local source_dir="$1"
  196. mkdir -p "$INSTALL_DIR" "$BUNDLE_ROOT"
  197. INSTALL_STAGE="$(mktemp -d "$BUNDLE_ROOT/.install.XXXXXX")"
  198. cp -R "$source_dir/." "$INSTALL_STAGE/"
  199. chmod 0755 "$INSTALL_STAGE/cs"
  200. local version_line version build_id final_dir next_link
  201. version_line="$("$INSTALL_STAGE/cs" --version)"
  202. version="${version_line##* }"
  203. case "$version" in
  204. ''|*[!A-Za-z0-9._-]*) err "Invalid cs version in release bundle: $version_line"; exit 1 ;;
  205. esac
  206. build_id="$(sha256_of "$INSTALL_STAGE/cs" | cut -c1-12)"
  207. final_dir="$BUNDLE_ROOT/v${version}-${build_id}"
  208. if [ -d "$final_dir" ]; then
  209. rm -rf "$INSTALL_STAGE"
  210. else
  211. mv "$INSTALL_STAGE" "$final_dir"
  212. fi
  213. INSTALL_STAGE=""
  214. stop_old_daemon
  215. # `current` must remain a symlink owned by this installer. Refuse to move a
  216. # real directory out of the way: it may contain user data from a custom
  217. # CS_BUNDLE_ROOT.
  218. if [ -e "$BUNDLE_ROOT/current" ] && [ ! -L "$BUNDLE_ROOT/current" ]; then
  219. err "$BUNDLE_ROOT/current exists and is not a symlink; refusing to replace it."
  220. exit 1
  221. fi
  222. next_link="$BUNDLE_ROOT/.current.$$"
  223. ln -s "$final_dir" "$next_link"
  224. replace_path_atomically "$next_link" "$BUNDLE_ROOT/current"
  225. # Atomic rename replaces either a previous symlink or the legacy regular
  226. # binary without ever exposing a missing `cs` path to Claude Code.
  227. next_link="$INSTALL_DIR/.cs.$$"
  228. ln -s "$BUNDLE_ROOT/current/cs" "$next_link"
  229. replace_path_atomically "$next_link" "$INSTALL_DIR/cs"
  230. ln -sfn "$INSTALL_DIR/cs" "$INSTALL_DIR/claude-statusbar"
  231. ln -sfn "$INSTALL_DIR/cs" "$INSTALL_DIR/cstatus"
  232. INSTALLED_BUNDLE_DIR="$final_dir"
  233. }
  234. # ---------------------------------------------------------------------------
  235. # prune_old_bundles KEEP_DIR — the new daemon is already running before this
  236. # executes, so no process needs a previous onedir version.
  237. #
  238. # One exception: an unattended `cs upgrade` runs *out of* an old bundle, and a
  239. # PyInstaller onedir binary dlopens its libraries lazily — deleting that dir
  240. # mid-run can kill the upgrade while it is still working. The updater passes
  241. # its own bundle in CS_KEEP_BUNDLE_DIR; the next upgrade prunes it once nothing
  242. # is running inside it.
  243. # ---------------------------------------------------------------------------
  244. prune_old_bundles() {
  245. local keep_dir="$1" old
  246. for old in "$BUNDLE_ROOT"/v*; do
  247. [ -e "$old" ] || continue
  248. [ "$old" = "$keep_dir" ] && continue
  249. [ -n "${CS_KEEP_BUNDLE_DIR:-}" ] && [ "$old" = "$CS_KEEP_BUNDLE_DIR" ] && continue
  250. [ -d "$old" ] && [ ! -L "$old" ] && rm -rf "$old"
  251. done
  252. }
  253. main() {
  254. command -v curl >/dev/null 2>&1 || { err "curl is required."; exit 1; }
  255. local asset
  256. asset="$(detect_asset)"
  257. [ -n "$asset" ] || fall_back_to_pip
  258. # CS_RELEASE_BASE_URL pins the download to one release. `cs upgrade` sets it
  259. # to the exact tag it decided to install, because `releases/latest/download`
  260. # lags for a while after publishing — long enough for an upgrade to fetch
  261. # the version it was upgrading away from. Also used by the offline
  262. # installer integration test.
  263. local base="${CS_RELEASE_BASE_URL:-https://github.com/${REPO}/releases/latest/download}"
  264. # NOTE: the scratch dir must be a global, not a `local`. The EXIT trap runs
  265. # after this function has already returned, so a local `tmp` is out of scope
  266. # by then — under `set -u` that ended the install with a bare
  267. # "tmp: unbound variable", and the temp dir was never cleaned up.
  268. TMP_DIR="$(mktemp -d)"
  269. local tmp="$TMP_DIR"
  270. # Prefer a stapled, notarized disk image on supported Macs. Only a genuine
  271. # 404 (or an absent offline fixture) permits the legacy tar path; a network
  272. # or server error must not silently downgrade the authenticity checks.
  273. if [ "$(uname -s)" = "Darwin" ]; then
  274. local dmg_asset="cs-darwin-arm64.dmg" status effective
  275. say "Checking for the notarized macOS disk image..."
  276. if status="$(curl -sSL -w '%{http_code} %{url_effective}' "$base/$dmg_asset" -o "$tmp/$dmg_asset")"; then
  277. effective="${status#* }"
  278. status="${status%% *}"
  279. if [ "$status" = "200" ] || [ "$status" = "000" ]; then
  280. verify_checksum "$base" "$dmg_asset" "$tmp"
  281. verify_apple_signature "$tmp/$dmg_asset"
  282. spctl --assess --type open --context context:primary-signature "$tmp/$dmg_asset" || {
  283. err "Gatekeeper did not accept the disk image; refusing to install."; exit 1;
  284. }
  285. ok "✓ Apple signature and notarization verified"
  286. mkdir -p "$tmp/mounted"
  287. hdiutil attach "$tmp/$dmg_asset" -readonly -nobrowse -noautoopen -mountpoint "$tmp/mounted" >/dev/null
  288. DMG_MOUNT="$tmp/mounted"
  289. verify_apple_signature "$DMG_MOUNT/cs/cs"
  290. verify_apple_signature "$DMG_MOUNT/cs/cs-python"
  291. install_onedir_bundle "$DMG_MOUNT/cs"
  292. finish_install "onedir" "$INSTALLED_BUNDLE_DIR"
  293. return
  294. elif [ "$status" = "404" ]; then
  295. if [[ "$base" == */download/v* && "$effective" != */download/v* ]]; then
  296. effective="$base/"
  297. fi
  298. if [[ "$base" == "https://github.com/$REPO/releases/latest/download" &&
  299. "$effective" != */download/v* ]]; then
  300. local latest
  301. latest="$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" |
  302. sed -n 's/.*"tag_name":[[:space:]]*"\(v[0-9]*\.[0-9]*\.[0-9]*\)".*/\1/p')"
  303. [ -n "$latest" ] || { err "Could not resolve the release; retry later."; exit 1; }
  304. effective="https://github.com/$REPO/releases/download/$latest/"
  305. fi
  306. if [[ "$effective" =~ /download/v([0-9]+)\.([0-9]+)\.([0-9]+)/ ]] &&
  307. { [ "${BASH_REMATCH[1]}" -gt 3 ] ||
  308. { [ "${BASH_REMATCH[1]}" -eq 3 ] && [ "${BASH_REMATCH[2]}" -ge 46 ]; }; }; then
  309. err "The notarized disk image is missing for this release; refusing to downgrade."
  310. exit 1
  311. fi
  312. else
  313. err "Disk image download returned HTTP $status; refusing to downgrade."; exit 1
  314. fi
  315. elif [[ "$base" != file://* ]]; then
  316. err "Disk image download failed; retry when the network is available."; exit 1
  317. fi
  318. fi
  319. say "Downloading $asset from the latest release..."
  320. if ! curl -fsSL "$base/$asset" -o "$tmp/$asset"; then
  321. warn "Download failed (no release asset yet?)."
  322. fall_back_to_pip
  323. fi
  324. verify_checksum "$base" "$asset" "$tmp"
  325. say "Extracting..."
  326. tar -xzf "$tmp/$asset" -C "$tmp"
  327. local install_mode bundle_dir
  328. if [ -x "$tmp/cs/cs" ]; then
  329. install_mode="onedir"
  330. install_onedir_bundle "$tmp/cs"
  331. bundle_dir="$INSTALLED_BUNDLE_DIR"
  332. ok "✓ Installed cs bundle → $bundle_dir"
  333. ok "✓ Linked cs → $INSTALL_DIR/cs ($("$INSTALL_DIR/cs" --version 2>/dev/null || echo 'version unknown'))"
  334. warn_about_duplicate_installs
  335. elif [ -f "$tmp/cs" ]; then
  336. # Transition compatibility: `main/install.sh` can be newer than the
  337. # latest Release for a short window while CI is still building the
  338. # first onedir asset. Keep old releases installable, but do not pretend
  339. # they have fixed the onefile extraction problem.
  340. install_mode="legacy-onefile"
  341. bundle_dir=""
  342. stop_old_daemon
  343. mkdir -p "$INSTALL_DIR"
  344. rm -f "$INSTALL_DIR/cs"
  345. install -m 0755 "$tmp/cs" "$INSTALL_DIR/cs"
  346. ln -sfn "$INSTALL_DIR/cs" "$INSTALL_DIR/claude-statusbar"
  347. ln -sfn "$INSTALL_DIR/cs" "$INSTALL_DIR/cstatus"
  348. warn "Installed a legacy onefile asset; update again after the new onedir Release finishes building."
  349. else
  350. err "Archive did not contain a 'cs' bundle."
  351. exit 1
  352. fi
  353. finish_install "$install_mode" "$bundle_dir"
  354. }
  355. finish_install() {
  356. local install_mode="$1" bundle_dir="$2"
  357. # Ensure the install dir is on PATH.
  358. if ! command -v cs >/dev/null 2>&1 || [ "$(command -v cs)" != "$INSTALL_DIR/cs" ]; then
  359. if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
  360. warn "$INSTALL_DIR is not on your PATH."
  361. if ask_yes_no "Append 'export PATH=\"$INSTALL_DIR:\$PATH\"' to ~/.bashrc and ~/.zshrc?"; then
  362. for rc in "$HOME/.bashrc" "$HOME/.zshrc"; do
  363. echo "export PATH=\"$INSTALL_DIR:\$PATH\"" >> "$rc" 2>/dev/null || true
  364. done
  365. ok "✓ PATH updated (open a new shell, or run: export PATH=\"$INSTALL_DIR:\$PATH\")"
  366. else
  367. warn "Skipped. Add $INSTALL_DIR to your PATH manually to use 'cs'."
  368. fi
  369. fi
  370. fi
  371. export PATH="$INSTALL_DIR:$PATH"
  372. say "Wiring Claude Code statusLine (cs --setup)..."
  373. local setup_ok=1
  374. if [ "${CS_SKIP_SETUP:-0}" = "1" ]; then
  375. setup_ok=0
  376. say "Binary installed; setup skipped."
  377. elif ! "$INSTALL_DIR/cs" --setup; then
  378. setup_ok=0
  379. warn "cs --setup reported an issue; run it manually if the bar doesn't appear."
  380. fi
  381. if [ "$install_mode" = "onedir" ] && [ "${CS_SKIP_SETUP:-0}" != "1" ]; then
  382. # The new process is onedir, so this scan cannot create another `_MEI`.
  383. # cleanup.py refuses to delete unless lsof proves the legacy directory
  384. # inactive; if that proof is unavailable, it leaves everything alone.
  385. "$INSTALL_DIR/cs" -m claude_statusbar.cleanup || true
  386. [ "$setup_ok" -eq 1 ] && prune_old_bundles "$bundle_dir"
  387. fi
  388. echo ""
  389. ok "═══════════════════════════════════════"
  390. ok "Install complete."
  391. ok "═══════════════════════════════════════"
  392. echo " Upgrade: live on the next statusline tick — no restart needed."
  393. echo " First install: restart Claude Code once so the status bar appears."
  394. echo " cs doctor # verify the wiring"
  395. echo " cs preview # try every style × theme"
  396. echo ""
  397. echo "Update later: curl -fsSL https://raw.githubusercontent.com/${REPO}/main/install.sh | bash"
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 434 on GitHub
  398. }
  399. main "$@"
scripts/sign_macos.py · Bundled script · 137 lines · 1 finding marked
  1. """Developer ID sign an onedir bundle and notarize its distributable DMG.
  2. Credentials stay in the keychain or environment. This script never exports a
  3. private key, changes keychain trust, or removes quarantine attributes.
  4. """
  5. import argparse
  6. import hashlib
  7. import json
  8. import os
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tempfile
  13. from pathlib import Path
  14. MACHO_MAGICS = {b'\xfe\xed\xfa\xce', b'\xce\xfa\xed\xfe',
  15. b'\xfe\xed\xfa\xcf', b'\xcf\xfa\xed\xfe',
  16. b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca',
  17. b'\xca\xfe\xba\xbf', b'\xbf\xba\xfe\xca'}
  18. def code_paths(bundle):
  19. """Sign nested code before the framework containers that seal it."""
  20. root = bundle.resolve()
  21. binaries, frameworks = [], []
  22. for path in bundle.rglob('*'):
  23. if path.is_symlink():
  24. if not path.resolve().is_relative_to(root):
  25. raise ValueError('bundle symlink escapes its root')
  26. continue
  27. if path.is_dir() and path.suffix == '.framework':
  28. frameworks.append(path)
  29. elif path.is_file():
  30. with path.open('rb') as source:
  31. if source.read(4) in MACHO_MAGICS:
  32. binaries.append(path)
  33. return sorted(binaries, key=lambda p: len(p.parts), reverse=True) + sorted(
  34. frameworks, key=lambda p: len(p.parts), reverse=True)
  35. def run(*args, **kwargs):
  36. subprocess.run(list(map(str, args)), check=True, **kwargs)
  37. def sign(bundle, identity, keychain=None):
  38. paths = code_paths(bundle)
  39. if not paths or not (bundle / 'cs').is_file() or not (bundle / 'cs-python').is_file():
  40. raise ValueError('expected a native cs + onedir Python runtime bundle')
  41. for path in paths:
  42. args = ['codesign', '--force', '--options', 'runtime', '--timestamp', '--sign', identity]
  43. if keychain:
  44. args += ['--keychain', keychain]
  45. if path == bundle / 'cs':
  46. args += ['--identifier', 'com.leeguoo.claude-statusbar.cli']
  47. elif path == bundle / 'cs-python':
  48. args += ['--identifier', 'com.leeguoo.claude-statusbar.runtime']
  49. run(*args, path)
  50. for path in paths:
  51. run('codesign', '--verify', '--strict', path)
  52. for path in (bundle / 'cs', bundle / 'cs-python'):
  53. details = subprocess.run(['codesign', '--display', '--verbose=4', str(path)],
  54. capture_output=True, text=True, check=True).stderr
  55. if ('Authority=Developer ID Application:' not in details
  56. or 'TeamIdentifier=6ZPXG4KVVS' not in details
  57. or '(runtime)' not in details):
  58. raise ValueError('unexpected signing identity or missing hardened runtime')
  59. return len(paths)
  60. def notarize(dmg, profile=None):
  61. args = ['xcrun', 'notarytool', 'submit', str(dmg), '--wait', '--timeout', '30m',
  62. '--output-format', 'json']
  63. if profile:
  64. args += ['--keychain-profile', profile]
  65. else:
  66. for name in ('ASC_KEY_PATH', 'ASC_KEY_ID', 'ASC_ISSUER_ID'):
  67. if not os.environ.get(name):
  68. raise ValueError('missing notarization configuration: ' + name)
  69. args += ['--key', os.environ['ASC_KEY_PATH'], '--key-id', os.environ['ASC_KEY_ID'],
  70. '--issuer', os.environ['ASC_ISSUER_ID']]
  71. result = subprocess.run(args, capture_output=True, text=True, check=True)
  72. data = json.loads(result.stdout)
  73. if data.get('status') != 'Accepted':
  74. raise RuntimeError('Apple notarization did not accept the DMG')
  75. run('xcrun', 'stapler', 'staple', dmg)
  76. run('xcrun', 'stapler', 'validate', dmg)
  77. run('spctl', '--assess', '--type', 'open', '--context', 'context:primary-signature', dmg)
  78. return data['id']
  79. def package(bundle, output, identity, keychain=None, profile=None):
  80. output.mkdir(parents=True, exist_ok=True)
  81. count = sign(bundle, identity, keychain)
  82. run(bundle / 'cs', '--version')
  83. run(bundle / 'cs', 'hud', 'check')
  84. dmg = output / 'cs-darwin-arm64.dmg'
  85. with tempfile.TemporaryDirectory(prefix='cs-dmg-') as tmp:
  86. stage = Path(tmp)
  87. shutil.copytree(bundle, stage / 'cs', symlinks=True)
  88. (stage / 'Install.txt').write_text(
  89. 'Claude Status Bar\n\nInstall or upgrade without sudo:\n'
  90. 'curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/install.sh | bash\n'
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 102 on GitHub
  91. '\nThis disk image includes the signed CLI, Python runtime and desktop HUD.\n',
  92. encoding='utf-8')
  93. run('hdiutil', 'create', '-volname', 'Claude Status Bar', '-srcfolder', stage,
  94. '-ov', '-format', 'UDZO', dmg, stdout=subprocess.DEVNULL)
  95. args = ['codesign', '--force', '--timestamp', '--sign', identity]
  96. if keychain:
  97. args += ['--keychain', keychain]
  98. run(*args, dmg)
  99. submission = notarize(dmg, profile)
  100. # Tar remains available for existing clients; these exact binary hashes
  101. # were scanned inside the notarized DMG. Only the DMG can carry a ticket.
  102. archive = output / 'cs-darwin-arm64.tar.gz'
  103. run('tar', '-czf', archive, '-C', bundle.parent, bundle.name)
  104. for path in (dmg, archive):
  105. digest = hashlib.sha256(path.read_bytes()).hexdigest()
  106. path.with_name(path.name + '.sha256').write_text(f'{digest} {path.name}\n')
  107. print(json.dumps({'signed_code_objects': count, 'notarization': 'Accepted',
  108. 'submission_id': submission, 'dmg': str(dmg)}))
  109. def main():
  110. parser = argparse.ArgumentParser(description=__doc__)
  111. parser.add_argument('bundle', type=Path)
  112. parser.add_argument('--output', required=True, type=Path)
  113. parser.add_argument('--identity', default=os.environ.get('SIGNING_IDENTITY', 'Developer ID Application'))
  114. parser.add_argument('--keychain', default=os.environ.get('SIGNING_KEYCHAIN'))
  115. parser.add_argument('--profile', default=os.environ.get('NOTARY_KEYCHAIN_PROFILE'))
  116. args = parser.parse_args()
  117. if sys.platform != 'darwin':
  118. raise SystemExit('macOS signing requires a Mac')
  119. package(args.bundle.resolve(), args.output.resolve(), args.identity, args.keychain, args.profile)
  120. if __name__ == '__main__':
  121. main()
web-install.sh · Bundled script · 369 lines · 1 finding marked
  1. #!/bin/bash
  2. # claude-statusbar — one-shot installer for `curl | bash` convenience.
  3. #
  4. # Usage (read the script first, please):
  5. # curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/web-install.sh -o /tmp/cs-install.sh
  6. # less /tmp/cs-install.sh # audit it
  7. # bash /tmp/cs-install.sh
  8. #
  9. # Or, if you trust this repo:
  10. # curl -fsSL https://raw.githubusercontent.com/leeguooooo/claude-code-usage-bar/main/web-install.sh | bash
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 10 on GitHub
  11. #
  12. # What this script does (full disclosure):
  13. # 1. Detects an available Python package manager (uv, pipx, or pip) and uses it
  14. # to install the `claude-statusbar` PyPI package. Nothing else is installed.
  15. # 2. Optionally writes `alias cs=...` and `alias cstatus=...` to your shell rc
  16. # file (~/.bashrc, ~/.zshrc, or fish config). Asks for [y/N] confirmation
  17. # first, reading from /dev/tty so the prompt works under `curl | bash`.
  18. # 3. Writes a `statusLine` block into ~/.claude/settings.json (backing up any
  19. # existing file first) so Claude Code picks up the bar on next launch.
  20. # 4. Runs `claude-statusbar --version` once to verify the install worked.
  21. #
  22. # What this script does NOT do:
  23. # - No `sudo`. Everything stays under $HOME.
  24. # - No silent install of any other package.
  25. # - No telemetry, no analytics, no calls to any author-controlled server.
  26. # The only remote endpoints touched are PyPI (or your chosen mirror) and,
  27. # if no package manager is found, https://astral.sh/uv/install.sh (the
  28. # official uv installer from Astral) — and that branch always prints a
  29. # warning so you can Ctrl-C.
  30. set -e
  31. GREEN='\033[0;32m'
  32. YELLOW='\033[1;33m'
  33. BLUE='\033[0;34m'
  34. RED='\033[0;31m'
  35. NC='\033[0m'
  36. echo -e "${BLUE}╔══════════════════════════════════════╗${NC}"
  37. echo -e "${BLUE}║ Claude Status Bar Quick Installer ║${NC}"
  38. echo -e "${BLUE}╚══════════════════════════════════════╝${NC}"
  39. echo ""
  40. # ----------------------------------------------------------------------------
  41. # ask_yes_no PROMPT
  42. #
  43. # Returns 0 on yes, 1 on no/timeout/no-tty. Reads from /dev/tty explicitly
  44. # because under `curl | bash` the script's own stdin is the piped HTTP body,
  45. # not the user's keyboard. If /dev/tty isn't available (e.g. inside a CI
  46. # container) we treat that as "no" so we never silently modify shell rc files.
  47. # ----------------------------------------------------------------------------
  48. ask_yes_no() {
  49. local prompt="$1"
  50. local reply
  51. if [ ! -r /dev/tty ]; then
  52. echo -e "${YELLOW}(no /dev/tty available — treating as 'no')${NC}"
  53. return 1
  54. fi
  55. printf "%s [y/N]: " "$prompt" > /dev/tty
  56. read -r reply < /dev/tty || return 1
  57. case "$reply" in
  58. y|Y|yes|YES) return 0 ;;
  59. *) return 1 ;;
  60. esac
  61. }
  62. # ----------------------------------------------------------------------------
  63. # detect_package_manager
  64. #
  65. # Prints "uv" | "pipx" | "pip" | "none" based on what's first on PATH.
  66. # Preference order chosen because uv > pipx > pip for isolation + speed.
  67. # ----------------------------------------------------------------------------
  68. detect_package_manager() {
  69. if command -v uv &> /dev/null; then
  70. echo "uv"
  71. elif command -v pipx &> /dev/null; then
  72. echo "pipx"
  73. elif command -v pip &> /dev/null || command -v pip3 &> /dev/null; then
  74. echo "pip"
  75. else
  76. echo "none"
  77. fi
  78. }
  79. # ----------------------------------------------------------------------------
  80. # show_current_version
  81. #
  82. # Print the currently-installed claude-statusbar version (if any) for context
  83. # so the user can see what they're upgrading from. Pure read; no side effects.
  84. # ----------------------------------------------------------------------------
  85. show_current_version() {
  86. if command -v claude-statusbar &> /dev/null; then
  87. local current_version
  88. current_version=$(claude-statusbar --version 2>/dev/null | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' || echo "unknown")
  89. echo -e "${YELLOW}Current version: ${current_version}${NC}"
  90. else
  91. echo -e "${YELLOW}Not currently installed${NC}"
  92. fi
  93. }
  94. # ----------------------------------------------------------------------------
  95. # install_package
  96. #
  97. # Calls the detected package manager to install (or upgrade) the
  98. # `claude-statusbar` PyPI package. Only this one package is installed.
  99. #
  100. # Per-channel commands:
  101. # uv → `uv tool install --upgrade claude-statusbar`
  102. # pipx → `pipx install --force claude-statusbar`
  103. # pip → `pip install --user --upgrade claude-statusbar` (+ PATH fix-up if
  104. # ~/.local/bin is missing from PATH; PATH fix-up writes are
  105. # confirmation-gated via ask_yes_no)
  106. # none → installs uv from https://astral.sh/uv/install.sh, then uv branch
  107. # (loud warning + confirmation before the chained curl|sh).
  108. # ----------------------------------------------------------------------------
  109. install_package() {
  110. local pm
  111. pm=$(detect_package_manager)
  112. echo -e "${BLUE}Installing/upgrading claude-statusbar...${NC}"
  113. show_current_version
  114. case $pm in
  115. uv)
  116. echo "Using uv (recommended)..."
  117. uv tool install --upgrade claude-statusbar
  118. ;;
  119. pipx)
  120. echo "Using pipx..."
  121. pipx install --force claude-statusbar
  122. ;;
  123. pip)
  124. echo "Using pip..."
  125. if command -v pip3 &> /dev/null; then
  126. pip3 install --user --upgrade claude-statusbar
  127. else
  128. pip install --user --upgrade claude-statusbar
  129. fi
  130. # pip --user puts binaries under ~/.local/bin. If that's not on
  131. # PATH the `cs` command won't be found. Offer to append to the
  132. # user's rc files, but only after explicit consent — modifying
  133. # shell startup is a shared-system change.
  134. if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
  135. echo -e "${YELLOW}~/.local/bin is not on your PATH.${NC}"
  136. if ask_yes_no "Append 'export PATH=\"\$HOME/.local/bin:\$PATH\"' to ~/.bashrc and ~/.zshrc?"; then
  137. echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc 2>/dev/null || true
  138. echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc 2>/dev/null || true
  139. export PATH="$HOME/.local/bin:$PATH"
  140. echo -e "${GREEN}✅ PATH updated.${NC}"
  141. else
  142. echo -e "${YELLOW}Skipped. You'll need to add ~/.local/bin to PATH manually.${NC}"
  143. export PATH="$HOME/.local/bin:$PATH"
  144. fi
  145. fi
  146. ;;
  147. none)
  148. # No Python tooling at all — the only way to bootstrap without
  149. # `sudo` is to install uv. uv's installer is itself a curl|sh
  150. # script; we warn the user and ask before chaining.
  151. echo -e "${YELLOW}No Python package manager found.${NC}"
  152. echo -e "${YELLOW}This step will download and run https://astral.sh/uv/install.sh${NC}"
  153. echo -e "${YELLOW}(official uv installer from Astral, the maintainers of ruff).${NC}"
  154. if ! ask_yes_no "Proceed with installing uv?"; then
  155. echo -e "${RED}Aborted. Install Python + pip manually, then re-run this script.${NC}"
  156. exit 1
  157. fi
  158. if [[ "$OSTYPE" == "msys" || "$OSTYPE" == "cygwin" || "$OSTYPE" == "win32" ]]; then
  159. powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
  160. else
  161. curl -LsSf https://astral.sh/uv/install.sh | sh
  162. fi
  163. # uv installs to ~/.local/bin or ~/.cargo/bin depending on platform.
  164. # Make both visible to this shell so the next `uv tool install` works.
  165. export PATH="$HOME/.local/bin:$PATH"
  166. export PATH="$HOME/.cargo/bin:$PATH"
  167. uv tool install --upgrade claude-statusbar
  168. ;;
  169. esac
  170. }
  171. # ----------------------------------------------------------------------------
  172. # configure_shell
  173. #
  174. # Optionally adds `alias cs=...` and `alias cstatus=...` to the user's shell
  175. # rc file. Confirmation-gated. Pure convenience — the `cs` script itself
  176. # ships an entry point under the same name, so skipping this just means the
  177. # user types `claude-statusbar` instead.
  178. # ----------------------------------------------------------------------------
  179. configure_shell() {
  180. echo -e "\n${BLUE}Shell aliases (optional)${NC}"
  181. local shell_name
  182. shell_name=$(basename "$SHELL")
  183. local config_file=""
  184. case "$shell_name" in
  185. bash) config_file="$HOME/.bashrc" ;;
  186. zsh) config_file="$HOME/.zshrc" ;;
  187. fish) config_file="$HOME/.config/fish/config.fish" ;;
  188. *) config_file="" ;;
  189. esac
  190. if [ -z "$config_file" ] || [ ! -f "$config_file" ]; then
  191. echo -e "${YELLOW}No supported shell rc file found. Skipping aliases.${NC}"
  192. return
  193. fi
  194. if grep -q "claude-statusbar" "$config_file" 2>/dev/null; then
  195. echo -e "${GREEN}✅ Aliases already configured in $config_file${NC}"
  196. return
  197. fi
  198. echo "Would append the following lines to $config_file:"
  199. echo " # Claude Status Bar Monitor"
  200. echo " alias cs='claude-statusbar'"
  201. echo " alias cstatus='claude-statusbar'"
  202. if ask_yes_no "Append?"; then
  203. {
  204. echo ""
  205. echo "# Claude Status Bar Monitor"
  206. echo "alias cs='claude-statusbar'"
  207. echo "alias cstatus='claude-statusbar'"
  208. } >> "$config_file"
  209. echo -e "${GREEN}✅ Aliases added to $config_file${NC}"
  210. else
  211. echo -e "${YELLOW}Skipped.${NC}"
  212. fi
  213. }
  214. # ----------------------------------------------------------------------------
  215. # configure_claude_statusbar
  216. #
  217. # Writes a `statusLine` block into ~/.claude/settings.json so Claude Code
  218. # loads the bar on next launch. If the file already exists it is backed up
  219. # to settings.json.backup.<timestamp> first (no overwrite without backup).
  220. #
  221. # The settings JSON is written via a Python helper, with the binary path
  222. # passed through an environment variable (CS_STATUSBAR_CMD) rather than
  223. # string-interpolated into the heredoc — avoids any shell quoting issues
  224. # if the path contains spaces or single quotes.
  225. # ----------------------------------------------------------------------------
  226. configure_claude_statusbar() {
  227. echo -e "\n${BLUE}Configuring Claude Code statusLine...${NC}"
  228. local claude_settings="$HOME/.claude/settings.json"
  229. # Prefer the canonical uv-tool binary path over ~/.local/bin symlinks so
  230. # auto-update via `uv tool install --upgrade` keeps pointing at the right
  231. # binary even if the symlink dance changes.
  232. local uv_tool_cmd="$HOME/.local/share/uv/tools/claude-statusbar/bin/claude-statusbar"
  233. local legacy_uv_tool_cmd="$HOME/.uv/tools/claude-statusbar/bin/claude-statusbar"
  234. local statusbar_cmd=""
  235. if [ -x "$uv_tool_cmd" ]; then
  236. statusbar_cmd="$uv_tool_cmd"
  237. elif [ -x "$legacy_uv_tool_cmd" ]; then
  238. statusbar_cmd="$legacy_uv_tool_cmd"
  239. else
  240. statusbar_cmd=$(which claude-statusbar 2>/dev/null)
  241. fi
  242. if [ -z "$statusbar_cmd" ]; then
  243. echo -e "${YELLOW}⚠️ claude-statusbar command not found in PATH${NC}"
  244. return
  245. fi
  246. mkdir -p "$HOME/.claude"
  247. if [ -f "$claude_settings" ]; then
  248. cp "$claude_settings" "$claude_settings.backup.$(date +%Y%m%d_%H%M%S)"
  249. echo -e "${GREEN}✅ Backed up existing settings${NC}"
  250. fi
  251. # Pass values via env vars, not via shell interpolation into the heredoc.
  252. # This eliminates the only potential injection surface in the script.
  253. export CS_SETTINGS_PATH="$claude_settings"
  254. export CS_STATUSBAR_CMD="$statusbar_cmd"
  255. if [ -f "$claude_settings" ] && [ -s "$claude_settings" ]; then
  256. python3 - <<'PY' || { echo -e "${YELLOW}⚠️ Failed to update settings${NC}"; return; }
  257. import json, os
  258. path = os.environ["CS_SETTINGS_PATH"]
  259. cmd = os.environ["CS_STATUSBAR_CMD"]
  260. try:
  261. with open(path) as f:
  262. settings = json.load(f)
  263. except Exception:
  264. settings = {}
  265. settings["statusLine"] = {"type": "command", "command": cmd, "padding": 0}
  266. with open(path, "w") as f:
  267. json.dump(settings, f, indent=2)
  268. print("✅ Updated Claude Code settings")
  269. PY
  270. else
  271. python3 - <<'PY' || { echo -e "${YELLOW}⚠️ Failed to create settings${NC}"; return; }
  272. import json, os
  273. path = os.environ["CS_SETTINGS_PATH"]
  274. cmd = os.environ["CS_STATUSBAR_CMD"]
  275. with open(path, "w") as f:
  276. json.dump({"statusLine": {"type": "command", "command": cmd, "padding": 0}}, f, indent=2)
  277. print("✅ Created Claude Code settings")
  278. PY
  279. fi
  280. echo -e "${GREEN}✅ Claude Code statusLine configured!${NC}"
  281. echo -e "${YELLOW}📝 Restart Claude Code to see the bar.${NC}"
  282. }
  283. # ----------------------------------------------------------------------------
  284. # test_installation
  285. #
  286. # Smoke-test: just verify that `claude-statusbar` is now resolvable and prints
  287. # a version. Does not run the bar rendering itself (that needs Claude Code
  288. # session data, which the install path doesn't have).
  289. # ----------------------------------------------------------------------------
  290. test_installation() {
  291. echo -e "\n${BLUE}Verifying install...${NC}"
  292. if command -v claude-statusbar &> /dev/null; then
  293. local new_version
  294. new_version=$(claude-statusbar --version 2>/dev/null | grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+' || echo "unknown")
  295. echo -e "${GREEN}✅ Installed: claude-statusbar ${new_version}${NC}"
  296. else
  297. echo -e "${RED}❌ claude-statusbar not on PATH after install${NC}"
  298. echo "Check the output above; you may need to open a new shell or run:"
  299. echo " export PATH=\"\$HOME/.local/bin:\$PATH\""
  300. exit 1
  301. fi
  302. }
  303. # ----------------------------------------------------------------------------
  304. # show_usage
  305. # ----------------------------------------------------------------------------
  306. show_usage() {
  307. echo -e "\n${GREEN}═══════════════════════════════════════${NC}"
  308. echo -e "${GREEN}Install complete.${NC}"
  309. echo -e "${GREEN}═══════════════════════════════════════${NC}"
  310. echo ""
  311. echo "Usage:"
  312. echo " claude-statusbar # full command"
  313. echo " cstatus # short alias (if you opted in)"
  314. echo " cs # shortest alias (if you opted in)"
  315. echo ""
  316. echo "Next steps:"
  317. echo " cs doctor # verify the wiring"
  318. echo " cs preview # try every style × theme"
  319. echo ""
  320. echo "Disable auto-update: export CLAUDE_STATUSBAR_NO_UPDATE=1"
  321. }
  322. # ----------------------------------------------------------------------------
  323. # main
  324. # ----------------------------------------------------------------------------
  325. main() {
  326. if ! command -v python3 &> /dev/null; then
  327. echo -e "${RED}Python 3 is required but not installed.${NC}"
  328. echo "Install Python 3.9+ from https://python.org and re-run."
  329. exit 1
  330. fi
  331. install_package
  332. configure_shell
  333. configure_claude_statusbar
  334. test_installation
  335. show_usage
  336. }
  337. main "$@"

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.