Skip to content
Back to search

snip

CLI proxy that reduces LLM token usage by 60-90%. Declarative YAML filters for Claude Code, Cursor, Copilot, Gemini. rtk alternative in Go.

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/edouard-claude--snip/badge.svg)](/listings/edouard-claude--snip)

HTML

<a href="/listings/edouard-claude--snip"><img src="/api/listings/edouard-claude--snip/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.

# Quick install (macOS/Linux)
curl -fsSL https://raw.githubusercontent.com/edouard-claude/snip/master/install.sh | sh

# Or via Homebrew
brew install edouard-claude/tap/snip

# Or with Go
go install github.com/edouard-claude/snip/cmd/snip@latest

# Then hook into Claude Code
snip init
# That's it. Every shell command Claude runs now goes through snip.

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.

SKILL.md · Manifest · 233 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # Creating snip Filters
  2. You are an expert at writing declarative YAML filters for **snip**, a CLI proxy that reduces LLM token consumption by filtering shell output.
  3. ## Filter File Location
  4. - **Built-in filters**: `filters/*.yaml` (embedded in the binary at build time)
  5. - **User filters**: `~/.config/snip/filters/*.yaml` (override built-in filters by name)
  6. - **Per-project filters**: configure additional directories via `filters.dir` array in `~/.config/snip/config.toml` (e.g. `dir = ["~/.config/snip/filters", "${env.PWD}/.snip"]`). Later directories take priority.
  7. **Trust store**: filters in any directory outside `~/.config/snip/` are ignored (with a stderr warning) until approved once with `snip trust <dir>`, which pins each file's SHA-256. Re-run `snip trust` after editing a trusted file.
  8. ## Filter Structure
  9. Every filter is a YAML file with this structure:
  10. ```yaml
  11. name: "tool-subcommand" # Required. Unique identifier, used for registry lookup.
  12. version: 1 # Informational revision number of the filter (bump on behavior change).
  13. description: "What this filter does" # Human-readable purpose.
  14. match: # Required. When to apply this filter.
  15. command: "tool" # Required. The CLI tool name (e.g., "git", "go", "npm").
  16. subcommand: "sub" # Optional. First non-flag argument (e.g., "test", "log").
  17. # Also accepts a list: ["install", "add", "i"]; include ""
  18. # in the list to match the bare command invocation too.
  19. exclude_flags: ["-v", "--json"] # Optional. Skip filter if user passes any of these.
  20. require_flags: ["--all"] # Optional. Only apply if user passes ALL of these.
  21. inject: # Optional. Modify command args before execution.
  22. args: ["--json"] # Arguments to append to the command.
  23. defaults: # Flag defaults, only added if flag not already present.
  24. "-n": "10"
  25. skip_if_present: ["--json"] # Don't inject anything if any of these flags are present.
  26. streams: ["stdout", "stderr"] # Optional. Which streams to filter. Default: ["stdout"].
  27. # Use ["stderr"] for tools that output to stderr (e.g., bun test).
  28. # Use ["stdout", "stderr"] to filter both streams merged together.
  29. pipeline: # Required. Ordered list of transformation actions.
  30. - action: "keep_lines"
  31. pattern: "\\S"
  32. - action: "head"
  33. n: 20
  34. on_error: "passthrough" # Descriptive convention: the engine ALWAYS falls back to raw
  35. # output when a pipeline fails; no other value is implemented.
  36. ```
  37. ## Match Rules
  38. - `command` is matched exactly against the first token of the shell command.
  39. - `subcommand` is matched against the first non-flag argument.
  40. - Flag matching uses **prefix matching**: `"-v"` matches both `-v` and `-verbose`.
  41. - Registry lookup is O(1) by key `"command"` or `"command:subcommand"`.
  42. ## Inject Behavior
  43. - Injected `args` are inserted before any `--` separator, otherwise appended.
  44. - `defaults` only apply if their flag key is not already present in the user's args.
  45. - If any flag in `skip_if_present` is found, the entire inject block is skipped.
  46. ## The 20 Pipeline Actions
  47. ### Line Filtering
  48. | Action | Params | Description |
  49. |--------|--------|-------------|
  50. | `keep_lines` | `pattern` (regex), `removed_msg` (fmt string with `%d`, optional) | Keep only lines matching the pattern. `removed_msg` appends a marker with the dropped count when N > 0 |
  51. | `remove_lines` | `pattern` (regex), `removed_msg` (fmt string with `%d`, optional) | Remove lines matching the pattern. `removed_msg` appends a marker with the dropped count when N > 0 |
  52. | `head` | `n` (int, default 10), `overflow_msg` (string, default "+{remaining} more lines") | Keep first N lines |
  53. | `tail` | `n` (int, default 10), `overflow_msg` (string, default "+{dropped} earlier lines") | Keep last N lines |
  54. | `dedup` | `normalize` ([]string of regexes to strip before comparing), `top` (int, 0=all) | Deduplicate lines, output "text (xN)" for repeats |
  55. ### Line Transformation
  56. | Action | Params | Description |
  57. |--------|--------|-------------|
  58. | `truncate_lines` | `max` (int, default 80), `ellipsis` (string, default "...") | Truncate long lines |
  59. | `replace` | `pattern` (regex), `replacement` (string, supports $1, $2...) | Regex find and replace on each line |
  60. | `truncate_bytes` | `max` (int, 0=disabled), `overflow_msg` (string, default "... truncated at {max} bytes") | Cap the whole output at `max` bytes, cutting on a UTF-8 rune boundary. The marker is paid for out of `max`, and is dropped when it alone would not fit |
  61. | `strip_ansi` | (none) | Remove ANSI escape codes |
  62. | `compact_path` | (none) | Strips a leading `src/`/`lib/`/`internal/`/`pkg/`/`vendor/` segment. The result may not resolve from the cwd, and carries no marker saying so — no bundled filter uses it. Display-only paths only. |
  63. ### Extraction & Grouping
  64. | Action | Params | Description |
  65. |--------|--------|-------------|
  66. | `regex_extract` | `pattern` (regex with capture groups), `format` (string using $0, $1, $2...) | Extract data via regex capture groups |
  67. | `group_by` | `pattern` (regex with capture group), `format` (template, default "{{.Key}}: {{.Count}}"), `top` (int) | Group lines by capture group, count occurrences |
  68. | `aggregate` | `patterns` (map of name->regex), `format` (Go template), `append` (bool) | Count lines matching named patterns. **Replaces** the input lines with the summary unless `append: true` (forgetting it caused bugs #134/#136: a correct count and no content) |
  69. | `state_machine` | `states` (map of state definitions with `keep`, `until`, `next`) | Stateful line filtering with transitions |
  70. ### JSON Processing
  71. | Action | Params | Description |
  72. |--------|--------|-------------|
  73. | `json_extract` | `fields` ([]string), `format` (template, optional) | Extract fields from JSON input |
  74. | `json_schema` | `max_depth` (int, default 3) | Output JSON type schema |
  75. | `ndjson_stream` | `group_by` (string field name), `format` (template with .Key, .Count, .Events) | Process newline-delimited JSON |
  76. ### Formatting & Conditionals
  77. | Action | Params | Description |
  78. |--------|--------|-------------|
  79. | `format_template` | `template` (Go text/template, required) | Format output using Go template |
  80. | `match_output` | `pattern` (regex), `message` (string, default "ok"), `unless` (regex) | If the whole output matches `pattern`, replace it with `message`; `unless` takes priority and passes through |
  81. | `on_empty` | `message` (string) | Return `message` when the output is empty or whitespace-only |
  82. ### Template Data for `format_template`
  83. The template receives:
  84. - `{{.lines}}` - all current lines joined with newlines
  85. - `{{.count}}` - number of lines
  86. - `{{.groups}}` - map from `group_by` action (if used earlier in pipeline)
  87. - `{{.stats}}` - map from `aggregate` action (if used earlier in pipeline)
  88. **`{{.count}}` trap**: it counts the lines *reaching the template*, not entities. After any stage that emits a summary, an overflow marker or a cap, the number is wrong (caused bug #125). Prefer the tool's own count over recomputing one.
  89. ### Metadata Flow Between Actions
  90. - `group_by` sets metadata `"groups"` (map[string]int)
  91. - `aggregate` sets metadata `"stats"` (map[string]int)
  92. - `format_template` can access both via `{{.groups}}` and `{{.stats}}`
  93. - All other actions pass metadata through unchanged
  94. ## Design Principles
  95. 1. **Start with `keep_lines` pattern `"\\S"`** to strip blank lines early.
  96. 2. **Use `inject` to request machine-readable output** (e.g., `--json`, `--porcelain`) then filter that structured data.
  97. 3. **Respect user intent**: use `exclude_flags` to skip filtering when the user explicitly requests a different format.
  98. 4. **Keep the conventional `on_error: "passthrough"` line**: it documents the engine's actual fallback behavior (raw output on any pipeline failure).
  99. 5. **Chain actions from broad to specific**: filter noise first, then extract, then format.
  100. 6. **Keep output minimal but useful**: the goal is 60-90% token reduction while preserving actionable information.
  101. ## Examples
  102. ### Simple: remove noise lines
  103. ```yaml
  104. name: "npm-install"
  105. version: 1
  106. description: "Condensed npm install output"
  107. match:
  108. command: "npm"
  109. subcommand: "install"
  110. pipeline:
  111. - action: "remove_lines"
  112. pattern: "^(npm warn|npm notice)"
  113. - action: "keep_lines"
  114. pattern: "\\S"
  115. - action: "aggregate"
  116. patterns:
  117. added: "^added "
  118. removed: "^removed "
  119. up_to_date: "up to date"
  120. format: "{{if gt .up_to_date 0}}up to date{{else}}{{.added}} added, {{.removed}} removed{{end}}"
  121. on_error: "passthrough"
  122. ```
  123. ### Intermediate: inject flags + extract structured data
  124. ```yaml
  125. name: "go-test"
  126. version: 1
  127. description: "Condensed go test output with pass/fail summary"
  128. match:
  129. command: "go"
  130. subcommand: "test"
  131. exclude_flags: ["-json", "-v", "-bench", "-run"]
  132. inject:
  133. args: ["-json"]
  134. skip_if_present: ["-json", "-v", "-bench"]
  135. pipeline:
  136. - action: "keep_lines"
  137. pattern: "\\S"
  138. - action: "keep_lines"
  139. pattern: "\"Test\":\""
  140. - action: "keep_lines"
  141. pattern: "\"Action\":\"(pass|fail)\""
  142. - action: "aggregate"
  143. patterns:
  144. passed: '"Action":"pass"'
  145. failed: '"Action":"fail"'
  146. format: "{{if and (eq .passed 0) (eq .failed 0)}}No tests found{{else}}{{.passed}} passed, {{.failed}} failed{{end}}"
  147. on_error: "passthrough"
  148. ```
  149. ### Advanced: state machine for multi-section output
  150. ```yaml
  151. name: "cargo-test"
  152. version: 2
  153. description: "cargo test summary lines, plus the failure report when a test fails"
  154. match:
  155. command: "cargo"
  156. subcommand: "test"
  157. pipeline:
  158. - action: "remove_lines"
  159. pattern: "^\\s*(Compiling|Downloading|Downloaded|Updating|Running|Executable)"
  160. - action: "keep_lines"
  161. pattern: "\\S"
  162. - action: "state_machine"
  163. states:
  164. start:
  165. keep: "^test result"
  166. until: "^failures"
  167. next: "failures"
  168. failures:
  169. keep: "."
  170. - action: "head"
  171. n: 150
  172. - action: "format_template"
  173. template: "{{.lines}}"
  174. on_error: "passthrough"
  175. ```
  176. The `until` on `start` is what makes this safe. Everything after the first
  177. `failures:` line is the failure report, and a panic message can hold any text at
  178. all — including a line that looks exactly like a test result. So every stage that
  179. drops or counts lines has to sit on the `start` side of that boundary, which
  180. `keep` does. A `remove_lines` placed after the state machine would instead run
  181. over the panic messages and delete them.
  182. ## Workflow to Create a New Filter
  183. 1. **Identify the command** and its typical verbose output.
  184. 2. **Run the command** and capture raw output to understand the structure.
  185. 3. **Decide what to keep**: what information does the LLM actually need?
  186. 4. **Check if the tool has a machine-readable flag** (--json, --porcelain, etc.) that would make filtering easier -- use `inject` if so.
  187. 5. **Write the pipeline**: strip blanks, filter/extract, aggregate, format.
  188. 6. **Test the filter** by placing it in `~/.config/snip/filters/` and running the command through snip.
  189. 7. **To contribute**: add the YAML to `filters/` in the repo and submit a PR.
README.md · README · 717 lines · 1 finding marked

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center">
  2. <img src="https://img.shields.io/github/v/release/edouard-claude/snip?style=flat-square" alt="Release">
  3. <img src="https://img.shields.io/github/actions/workflow/status/edouard-claude/snip/ci.yaml?branch=master&style=flat-square&label=CI" alt="CI">
  4. <img src="https://img.shields.io/github/license/edouard-claude/snip?style=flat-square" alt="License">
  5. <img src="https://img.shields.io/badge/Go-1.25+-00ADD8?style=flat-square&logo=go" alt="Go">
  6. </p>
  7. # snip - Reduce LLM Token Usage by 60-90%
  8. **CLI proxy that filters shell output before it reaches your AI coding assistant's context window.** Works with Claude Code, Cursor, Copilot, Gemini CLI, Windsurf, Cline, Codex, Pi, Grok Build, Kilo Code, Antigravity, OpenCode, OpenClaw, Aider, and any tool that runs shell commands.
  9. AI coding agents burn tokens on verbose shell output that adds zero signal. A passing `go test` produces hundreds of lines the LLM will never use. `git log` dumps full commit metadata when a one-liner per commit suffices.
  10. snip sits between your AI tool and the shell, filtering output through **declarative YAML pipelines**. Write a YAML file, drop it in a folder, done. The extensible LLM token optimizer: filters are YAML data files, not compiled code.
  11. ```
  12. snip — Token Savings Report
  13. ══════════════════════════════
  14. Commands filtered 128
  15. Tokens saved 2.3M
  16. Avg savings 99.8%
  17. Efficiency Elite
  18. Total time 725.9s
  19. ███████████████████░ 100%
  20. 14-day trend ▁█▇
  21. Top commands by tokens saved
  22. Command Runs Saved Savings Impact
  23. ───────────────────────── ──── ────── ─────── ────────────
  24. go test ./... 8 806.2K 99.8% ████████████
  25. go test ./pkg/... 3 482.9K 99.8% ███████░░░░░
  26. go test ./... -count=1 3 482.0K 99.8% ███████░░░░░
  27. ```
  28. > Measured on a real Claude Code session — 128 commands, 2.3M tokens saved.
  29. ## Quick Start
  30. ```bash
  31. # Quick install (macOS/Linux)
  32. curl -fsSL https://raw.githubusercontent.com/edouard-claude/snip/master/install.sh | sh
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 45 on GitHub
  33. # Or via Homebrew
  34. brew install edouard-claude/tap/snip
  35. # Or with Go
  36. go install github.com/edouard-claude/snip/cmd/snip@latest
  37. # Then hook into Claude Code
  38. snip init
  39. # That's it. Every shell command Claude runs now goes through snip.
  40. ```
  41. ## How It Works
  42. **Before** — Claude Code sees this (275 tokens):
  43. ```
  44. $ go test ./...
  45. ok github.com/edouard-claude/snip 13.697s
  46. ? github.com/edouard-claude/snip/cmd/snip [no test files]
  47. ok github.com/edouard-claude/snip/internal/cli 1.357s
  48. ok github.com/edouard-claude/snip/internal/config 1.898s
  49. ok github.com/edouard-claude/snip/internal/discover 4.271s
  50. ok github.com/edouard-claude/snip/internal/display 2.516s
  51. ok github.com/edouard-claude/snip/internal/economics 3.073s
  52. ok github.com/edouard-claude/snip/internal/engine 5.262s
  53. ok github.com/edouard-claude/snip/internal/filter 3.687s
  54. ok github.com/edouard-claude/snip/internal/hook 4.555s
  55. ok github.com/edouard-claude/snip/internal/hookaudit 4.560s
  56. ok github.com/edouard-claude/snip/internal/initcmd 4.534s
  57. ok github.com/edouard-claude/snip/internal/inspect 4.598s
  58. ok github.com/edouard-claude/snip/internal/learn 4.474s
  59. ok github.com/edouard-claude/snip/internal/tee 4.430s
  60. ok github.com/edouard-claude/snip/internal/tracking 4.055s
  61. ok github.com/edouard-claude/snip/internal/trust 4.544s
  62. ok github.com/edouard-claude/snip/internal/utils 4.528s
  63. ok github.com/edouard-claude/snip/internal/verify 4.517s
  64. ```
  65. **After** — snip returns this (8 tokens):
  66. ```
  67. 1125 passed, 0 failed
  68. ```
  69. That's **97% fewer tokens**, measured on this very repository. The filter injects `-json` and counts individual test results, so the LLM gets more signal — 1125 tests passed, not just 18 packages — in a fraction of the space.
  70. ```
  71. ┌─────────────┐ ┌─────────────────┐ ┌──────────────┐ ┌────────────┐
  72. │ Claude Code │────>│ snip intercept │────>│ run command │────>│ filter │
  73. │ runs git │ │ match filter │ │ capture I/O │ │ pipeline │
  74. └─────────────┘ └─────────────────┘ └──────────────┘ └─────┬──────┘
  75. │
  76. ┌─────────────────┐ ┌──────────────┐ │
  77. │ Claude Code │<────│ track savings│<──────────┘
  78. │ sees filtered │ │ in SQLite │
  79. └─────────────────┘ └──────────────┘
  80. ```
  81. No filter match? The command passes through unchanged — zero overhead.
  82. ### Token Savings by Command
  83. | Command | Before | After | Reduction |
  84. |---------|-------:|------:|----------:|
  85. | `cargo test` | 591 tokens | 5 tokens | **99.2%** |
  86. | `go test ./...` | 275 tokens | 8 tokens | **97.1%** |
  87. | `git log` | 371 tokens | 53 tokens | **85.7%** |
  88. | `git status` | 112 tokens | 16 tokens | **85.7%** |
  89. | `git diff` | 355 tokens | 66 tokens | **81.4%** |
  90. Stop wasting tokens on noise. snip gives the LLM the same signal in a fraction of the context window.
  91. ## Installation
  92. ### Homebrew (recommended)
  93. ```bash
  94. brew install edouard-claude/tap/snip
  95. ```
  96. ### From GitHub Releases
  97. Download the latest binary for your platform from [Releases](https://github.com/edouard-claude/snip/releases).
  98. ```bash
  99. # macOS (Apple Silicon)
  100. curl -Lo snip.tar.gz https://github.com/edouard-claude/snip/releases/latest/download/snip_$(curl -s https://api.github.com/repos/edouard-claude/snip/releases/latest | grep tag_name | cut -d'"' -f4 | tr -d v)_darwin_arm64.tar.gz
  101. tar xzf snip.tar.gz && mv snip /usr/local/bin/
  102. ```
  103. ### From source
  104. ```bash
  105. go install github.com/edouard-claude/snip/cmd/snip@latest
  106. ```
  107. Or build locally:
  108. ```bash
  109. git clone https://github.com/edouard-claude/snip.git
  110. cd snip && make install
  111. ```
  112. `make install` and `make install-lite` use the first available destination:
  113. an explicit `GOBIN`, `go env GOBIN`, or the first `go env GOPATH` entry plus
  114. `/bin`. Use `make upgrade` or `make upgrade-lite` to replace the resolved
  115. `snip` on `PATH` instead. An explicit `GOBIN` overrides the upgrade destination.
  116. Requires Go 1.25+.
  117. ## Supported AI Tools
  118. snip integrates with every major AI coding assistant. One binary, universal compatibility.
  119. | Tool | Install | Method |
  120. |------|---------|--------|
  121. | **Claude Code** | `snip init` | PreToolUse hook (native) |
  122. | **Cursor** | `snip init --agent cursor` | beforeShellExecution hook (native) |
  123. | **GitHub Copilot** | `snip init --agent copilot` | preToolUse hook (native) |
  124. | **Gemini CLI** | `snip init --agent gemini` | GEMINI.md prompt injection |
  125. | **Codex (OpenAI)** | `snip init --agent codex` | PreToolUse hook (native) |
  126. | **Pi (pi.dev)** | `snip init --agent pi` | PreToolUse hook (via [pi-hooks](https://github.com/hsingjui/pi-hooks)) |
  127. | **Grok Build (xAI)** | `snip init --agent grok` | PreToolUse hook (deny + re-run suggestion) |
  128. | **Windsurf** | `snip init --agent windsurf` | .windsurfrules prompt injection |
  129. | **Cline / Roo Code** | `snip init --agent cline` | .clinerules prompt injection |
  130. | **Kilo Code** | `snip init --agent kilocode` | .kilocode/rules/ prompt injection |
  131. | **Antigravity** | `snip init --agent antigravity` | PreToolUse hook (native) |
  132. | **OpenCode** | [opencode-snip](https://github.com/VincentHardouin/opencode-snip) plugin | tool.execute.before hook |
  133. | **OpenClaw** | `openclaw plugins install openclaw-snip` | plugin |
  134. | **Aider** | shell aliases | prefix commands with snip |
  135. ### Claude Code
  136. ```bash
  137. snip init
  138. ```
  139. This installs a `PreToolUse` hook that transparently rewrites supported commands. Claude Code never sees the substitution -- it receives compressed output as if the original command produced it.
  140. Supported commands: 132 filters covering 100 distinct commands: git, go, cargo, npm, yarn, pnpm, docker, kubectl, terraform, aws, gh, dotnet, and many more.
  141. ```bash
  142. snip init --uninstall # remove the hook
  143. ```
  144. ### Cursor
  145. ```bash
  146. snip init --agent cursor
  147. ```
  148. This patches `~/.cursor/hooks.json` with a `beforeShellExecution` hook. Works the same way as Claude Code.
  149. ```bash
  150. snip init --agent cursor --uninstall # remove the hook
  151. ```
  152. ### Pi (pi.dev)
  153. ```bash
  154. snip init --agent pi
  155. ```
  156. This patches `~/.pi/agent/settings.json` with a `PreToolUse` entry matching the `bash` tool. The runtime hook is interpreted by the community extension [`@hsingjui/pi-hooks`](https://github.com/hsingjui/pi-hooks), which mirrors Claude Code's `hookSpecificOutput` format (including command rewriting via `updatedInput`). Install it once:
  157. ```bash
  158. pi install npm:@hsingjui/pi-hooks
  159. ```
  160. Then run `/reload` (or restart Pi). Once active, snip rewrites supported commands transparently.
  161. ```bash
  162. snip init --agent pi --uninstall # remove the hook
  163. ```
  164. ### Grok Build (xAI)
  165. ```bash
  166. snip init --agent grok
  167. ```
  168. This writes `~/.grok/hooks/snip.json` with a `PreToolUse` hook matching the shell tool. Grok Build hooks cannot rewrite commands in place (the hook contract is allow/deny only), so snip denies matched commands with a re-run suggestion (`"…/snip" run -- <command>`). Non-matching commands pass through untouched, and the hook is fail-open: if snip breaks, commands simply run unfiltered.
  169. Prefer prompt injection instead? Grok Build reads `AGENTS.md` natively:
  170. ```bash
  171. snip init --agent grok --mode prompt # creates AGENTS.md
  172. snip init --agent grok --uninstall # remove the hook
  173. ```
  174. `AGENTS.md` is shared with Codex, so `--uninstall` never deletes it; it prints a reminder instead.
  175. ### Codex
  176. ```bash
  177. snip init --agent codex
  178. ```
  179. This patches `~/.codex/hooks.json` with a native `PreToolUse` hook. Supported shell commands are transparently rewritten through snip with Codex's `updatedInput` contract, so the model runs commands normally and sees only the filtered output.
  180. For safety, mixed commands containing unsupported segments, pipelines with uninspected tails, and command substitutions pass through unchanged so Codex keeps its native permission flow.
  181. Use `snip proxy -- <command>` when full unfiltered output is required.
  182. ```bash
  183. snip init --agent codex --uninstall
  184. ```
  185. Codex CLI 0.131.0 or later is required for `PreToolUse` input rewriting. For older releases, use the legacy project-scoped prompt integration:
  186. ```bash
  187. snip init --agent codex --mode prompt
  188. ```
  189. ### GitHub Copilot
  190. ```bash
  191. snip init --agent copilot
  192. ```
  193. This patches `~/.copilot/hooks/snip.json` with a native `preToolUse` hook that rewrites supported commands transparently, like Claude Code.
  194. Prefer prompt injection instead? Use the legacy project-scoped mode:
  195. ```bash
  196. snip init --agent copilot --mode prompt # creates .github/copilot-instructions.md
  197. snip init --agent copilot --uninstall # remove the hook
  198. ```
  199. ### Antigravity
  200. `PreToolUse` is supported. This patches `~/.gemini/config/hooks.json`.
  201. ```bash
  202. snip init --agent antigravity
  203. ```
  204. ### Gemini / Windsurf / Cline / Kilo Code
  205. ```bash
  206. snip init --agent gemini # creates GEMINI.md
  207. snip init --agent windsurf # creates .windsurfrules
  208. snip init --agent cline # creates .clinerules
  209. snip init --agent kilocode # creates .kilocode/rules/snip-rules.md
  210. ```
  211. These agents use prompt injection: a markdown file instructs the LLM to prefix shell commands with snip. Project-scoped (created in the current directory).
  212. ### OpenCode
  213. Install the [opencode-snip](https://github.com/VincentHardouin/opencode-snip) plugin by adding it to your OpenCode config (`~/.config/opencode/opencode.json`):
  214. ```json
  215. {
  216. "$schema": "https://opencode.ai/config.json",
  217. "plugin": ["opencode-snip@latest"]
  218. }
  219. ```
  220. The plugin uses the `tool.execute.before` hook to automatically prefix all commands with `snip`. Commands not supported by snip pass through unchanged.
  221. ### OpenClaw
  222. ```bash
  223. openclaw plugins install openclaw-snip
  224. ```
  225. ### Aider
  226. Use shell aliases to route commands through snip:
  227. ```bash
  228. # Add to ~/.bashrc or ~/.zshrc
  229. alias git="snip git"
  230. alias go="snip go"
  231. alias cargo="snip cargo"
  232. ```
  233. Or instruct the LLM via system prompt to prefix commands with `snip`.
  234. ### Standalone
  235. snip works without any AI tool:
  236. ```bash
  237. snip git log -10
  238. snip go test ./...
  239. snip gain # token savings report
  240. ```
  241. ## Usage
  242. ```bash
  243. snip <command> [args] # filter a command (implicit)
  244. snip run -- <command> # same, with explicit separator
  245. snip check -- <command> # check if a command would be filtered
  246. snip proxy <command> # force passthrough (no filtering)
  247. snip proxy -- <command> # same, with explicit separator
  248. snip gain # full dashboard (summary + sparkline + top commands)
  249. snip gain --daily # daily breakdown
  250. snip gain --weekly # weekly breakdown
  251. snip gain --monthly # monthly breakdown
  252. snip gain --top 10 # top N commands by tokens saved
  253. snip gain --history 20 # last 20 commands
  254. snip gain --quota # savings against plan quotas
  255. snip gain --unfiltered # opt-in report on unfiltered commands
  256. snip gain --no-truncate # disable command truncation
  257. snip gain --json # machine-readable output
  258. snip gain --csv # CSV export
  259. snip cc-economics # financial impact by pricing tier (configurable)
  260. snip discover # find missed savings in Claude Code history
  261. snip discover --since 30 # scan last 30 days
  262. snip discover --all # scan all projects
  263. snip learn # detect CLI error-correction patterns in sessions
  264. snip learn --since 7 # scan last 7 days (default 30)
  265. snip learn --all # scan all projects
  266. snip learn --generate # write .claude/rules/cli-corrections.md
  267. snip verify # run the filters' inline tests
  268. snip config # show config
  269. snip trust [path] # trust project-local filter file(s) by SHA-256
  270. snip untrust [path] # remove file(s) from the trust store
  271. snip hook # agent PreToolUse handler (used by the hooks)
  272. snip hook-audit # show recent hook activity (SNIP_HOOK_AUDIT=1)
  273. snip init # install Claude Code hook
  274. snip init --agent cursor # install Cursor hook
  275. snip init --agent pi # install Pi (pi.dev) hook
  276. snip init --agent copilot # install Copilot hook
  277. snip init --agent gemini # install Gemini CLI integration
  278. snip init --agent kilocode # install Kilo Code integration
  279. snip init --agent antigravity # install Antigravity integration
  280. snip init --uninstall # remove hook
  281. ```
  282. Global flags: `-v`/`-vv` (verbose, stackable), `-u` (ultra-compact), `--skip-env`, `--version`, `--help`.
  283. ## Filters
  284. Filters are declarative YAML files. The binary is the engine, filters are data — the two evolve independently.
  285. ```yaml
  286. name: "git-log"
  287. version: 1
  288. description: "Condense git log to hash + message"
  289. match:
  290. command: "git"
  291. subcommand: "log"
  292. exclude_flags: ["--format", "--pretty", "--oneline"]
  293. inject:
  294. args: ["--pretty=format:%h %s (%ar) <%an>", "--no-merges"]
  295. defaults:
  296. "-n": "10"
  297. pipeline:
  298. - action: "keep_lines"
  299. pattern: "\\S"
  300. - action: "truncate_lines"
  301. max: 80
  302. - action: "format_template"
  303. template: "{{.count}} commits:\n{{.lines}}"
  304. on_error: "passthrough"
  305. ```
  306. `match.subcommand` can be a scalar string (as above) or a list of exact subcommands:
  307. ```yaml
  308. match:
  309. command: "npm"
  310. subcommand: ["install", "add", "i"]
  311. ```
  312. If `subcommand` is omitted, the filter matches every subcommand for that command. To match only a bare command invocation, include an explicit empty string, for example `subcommand: ["", "install"]` to match `yarn` and `yarn install` without matching `yarn why`.
  313. ### 132 Built-in Filters
  314. snip ships with **132 declarative YAML filters** covering all major developer tools:
  315. | Category | Filters |
  316. |----------|---------|
  317. | **Git** (12) | status, log, diff, show, add, commit, push, pull, branch, fetch, stash, worktree |
  318. | **GitHub CLI** (3) | gh pr, gh issue, gh run |
  319. | **Go** (4) | go test, go build, go vet, golangci-lint |
  320. | **Rust** (7) | cargo test/build/check/clippy/install/nextest, rustc |
  321. | **Python** (11) | pytest, ruff, mypy, basedpyright, ty, pip, poetry, uv add/lock/remove/sync |
  322. | **JavaScript/TypeScript** (17) | jest, vitest, eslint, tsc, biome, oxlint, prettier, next, playwright, nx, turbo, npm, npx, yarn, pnpm install/list, prisma |
  323. | **Ruby** (6) | rspec, rubocop, rake, bundle, rails migrate, rails routes |
  324. | **.NET** (3) | dotnet build/test/format |
  325. | **Elixir** (2) | mix compile, mix format |
  326. | **Docker/K8s** (7) | docker build/ps/images/logs/compose, kubectl get/logs |
  327. | **Cloud/Infra** (6) | terraform, tofu, helm, ansible-playbook, gcloud, aws |
  328. | **Build tools** (14) | make, gcc, g++, gradle, gradlew, gradlew.bat, mvn, swift, xcodebuild, just, task, pio, trunk, mise |
  329. | **Files/Search** (7) | ls, find, grep, rg, diff, wc, tree |
  330. | **Linting** (6) | shellcheck, hadolint, markdownlint, markdownlint-cli2, yamllint, pre-commit |
  331. | **Package managers** (2) | brew, composer |
  332. | **System/Network** (14) | curl, wget, psql, jq, ping, ssh, rsync, df, du, ps, systemctl, iptables, stat, fail2ban |
  333. | **Other** (11) | jira, jj, yadm, gt, ollama, sops, skopeo, shopify, quarto, liquibase, spring-boot |
  334. Run `snip discover` to see which of your commands already have filters.
  335. ### 20 Pipeline Actions
  336. | Action | Description |
  337. |--------|-------------|
  338. | `keep_lines` | Keep lines matching regex |
  339. | `remove_lines` | Remove lines matching regex |
  340. | `truncate_lines` | Truncate lines to max length |
  341. | `truncate_bytes` | Hard cap on output size in bytes |
  342. | `strip_ansi` | Remove ANSI escape codes |
  343. | `head` / `tail` | Keep first/last N lines |
  344. | `group_by` | Group lines by regex capture |
  345. | `dedup` | Deduplicate with optional normalization |
  346. | `json_extract` | Extract fields from JSON |
  347. | `json_schema` | Infer schema from JSON |
  348. | `ndjson_stream` | Process newline-delimited JSON |
  349. | `regex_extract` | Extract regex captures |
  350. | `state_machine` | Multi-state line processing |
  351. | `aggregate` | Count pattern matches |
  352. | `format_template` | Go template formatting |
  353. | `compact_path` | Shorten file paths (see caveat below) |
  354. | `replace` | Regex find and replace |
  355. | `match_output` | Conditional short-circuit (return message if pattern matches) |
  356. | `on_empty` | Return message if output is empty |
  357. > **`compact_path` emits paths that may not resolve.** It strips a leading
  358. > `src/`, `lib/`, `internal/`, `pkg/` or `vendor/` segment unconditionally and
  359. > with no marker, so `internal/soak/report.go` becomes `soak/report.go` — which
  360. > `ENOENT`s from the directory the command ran in. No bundled filter uses it.
  361. > Reach for it only when the path is display-only and will never be opened.
  362. ### Custom Filters
  363. ```bash
  364. snip init # creates ~/.config/snip/filters/
  365. vim ~/.config/snip/filters/my-tool.yaml # add your filter
  366. ```
  367. User filters take priority over built-in ones. Later directories in the list override earlier ones.
  368. Filters under `~/.config/snip/` are always loaded. Filters anywhere else (for example a project's `.snip/` directory) must be approved once with `snip trust`, otherwise they are skipped:
  369. ```bash
  370. snip trust .snip/filters # approve the project's filters (SHA-256 pinned)
  371. ```
  372. Editing a trusted file invalidates its hash; run `snip trust` again after changes.
  373. ## Configuration
  374. Optional TOML config at `~/.config/snip/config.toml` (override the path with `SNIP_CONFIG`):
  375. ```toml
  376. # mode = "user" # "project" in a .snip/config.toml lets that file
  377. # override user settings (see Project Configuration)
  378. [tracking]
  379. db_path = "~/.local/share/snip/tracking.db"
  380. track_unfiltered = false # opt-in: also record commands that had no filter
  381. [display]
  382. color = true
  383. emoji = true
  384. quiet_no_filter = false # suppress "no filter" stderr messages
  385. summary = false # prepend a "[snip: ...]" line showing which filter/args were applied
  386. [filters]
  387. dir = "~/.config/snip/filters"
  388. [filters.enable]
  389. # git-diff = false # disable a specific built-in filter
  390. [filters.global] # safety caps appended to every filter's pipeline (0 = unlimited)
  391. # max_lines = 0 # cap the number of output lines
  392. # max_line_length = 0 # cap each line's length
  393. # max_output_bytes = 0 # hard cap on the bytes any filter emits.
  394. # Applied last, cutting on a UTF-8 rune boundary and
  395. # appending a "... truncated at N bytes" marker that is
  396. # counted inside the cap.
  397. [filters.override.dotnet-test] # tune a single filter without rewriting it
  398. # head = 200 # raise dotnet-test's cap from 40 to 200 lines
  399. # stream_mode = "full" # or skip this filter's pipeline entirely
  400. # Other overridable keys: tail, truncate_lines, keep_lines, remove_lines
  401. [filters.bypass]
  402. # commands = ["dotnet publish"] # always run these unfiltered
  403. [economics.tiers] # pricing for `snip cc-economics`, $ per 1M input tokens
  404. # haiku = 1.00 # free-form names; defaults are current Anthropic list
  405. # negotiated_opus = 3.10 # prices (haiku 1, sonnet 3, opus 5, fable 10) until set
  406. [tee]
  407. enabled = true
  408. mode = "failures" # "failures" | "always" | "never"
  409. max_files = 20
  410. max_file_size = 1048576
  411. # project_marker = ".git" # write tee files to <repo-root>/.snip/tee/ instead
  412. # of the global dir when the marker is found by
  413. # walking up from the working directory; a
  414. # .gitignore is created there so logs are never
  415. # committed, and snip falls back to the global dir
  416. # if the repo root is not writable
  417. ```
  418. > Override values must be positive: `head = 0` does not remove a filter's
  419. > truncation, it is ignored. To get unlimited output from one filter, use
  420. > `stream_mode = "full"` in its override block.
  421. Full reference for every key, default and merge rule: [Configuration wiki page](https://github.com/edouard-claude/snip/wiki/Configuration).
  422. ### Verify Your Configuration
  423. Every setting above is reproducible. To prove one is active without touching your real config, point `SNIP_CONFIG` at a scratch file:
  424. ```bash
  425. cd "$(mktemp -d)" && touch a.go b.md c.txt
  426. export SNIP_CONFIG=$PWD/test.toml
  427. printf '[filters.override.ls]\nhead = 2\n' > test.toml
  428. snip ls # 2 entries + "... +more entries (truncated by snip)"
  429. printf '[filters.bypass]\ncommands = ["ls"]\n' > test.toml
  430. snip ls # raw ls output, no filtering
  431. unset SNIP_CONFIG
  432. ```
  433. `snip config` prints the user config snip loads, `snip check -- <command>` names the filter that would handle a command, and `snip -v <command>` shows the filter and injected args as it runs.
  434. ### Project Configuration
  435. A repo can ship its own `.snip/config.toml`; snip walks up from the working directory and uses the first one it finds. The file must be trusted once (`snip trust .snip/config.toml`) and declare `mode = "project"` to override the user config. Project keys that participate in the merge: `filters.enable`, `filters.global`, `filters.override` (project wins), and `filters.bypass.commands` (concatenated, regardless of mode). Typical corporate setup: defaults for every developer live in the repo, personal tweaks stay in `~/.config/snip/config.toml`.
  436. ### Plugin Configuration
  437. An agent plugin (for example a Claude Code plugin) can ship a snip config that applies on every machine as the **base** of the cascade `plugin < user < project`. The plugin's hook exports the path:
  438. ```bash
  439. SNIP_PLUGIN_CONFIG=${CLAUDE_PLUGIN_ROOT}/snip/config.toml
  440. ```
  441. The file is a regular snip TOML restricted to the filter sections (`filters.enable`, `filters.global`, `filters.override`, `filters.bypass`, `transparent_prefixes`, and `filters.dir` so the plugin can ship its own filter YAMLs; plugin filters load first, so user filters win by name). A relative `filters.dir` resolves against the TOML's own directory, so `dir = "filters"` just works. The variable only needs to exist in the hook's environment: rewritten commands carry the path along as a `--plugin-config` flag, so the agent's shell needs no special environment. Like a project config, it must be trusted once:
  442. ```bash
  443. snip trust "$SNIP_PLUGIN_CONFIG" # the config itself
  444. snip trust "${SNIP_PLUGIN_CONFIG%/*}/filters" # the plugin's filters
  445. ```
  446. A plugin typically runs both commands from a session-start hook, so plugin updates re-trust automatically. Anything the user or the repo sets overrides the plugin layer. Full details on the [Configuration wiki page](https://github.com/edouard-claude/snip/wiki/Configuration).
  447. ```toml
  448. # .snip/config.toml — checked into the repo
  449. mode = "project"
  450. [filters.override.dotnet-test]
  451. head = 500 # this monorepo runs thousands of tests
  452. [filters.bypass]
  453. commands = ["dotnet publish"]
  454. ```
  455. ### Multiple Filter Directories
  456. `filters.dir` accepts a single string or an array of directories. This enables per-project filter rules alongside global ones:
  457. ```toml
  458. [filters]
  459. dir = [
  460. "~/.config/snip/filters",
  461. "${env.PWD}/.snip",
  462. ]
  463. ```
  464. Later directories take priority: a filter in `.snip/` overrides one with the same name in `~/.config/snip/filters/`.
  465. Directories outside `~/.config/snip/` go through the trust store: run `snip trust ${PWD}/.snip` once per project (and after each edit), or the files in it are silently skipped.
  466. ### Environment Variable Expansion
  467. `tracking.db_path` and `filters.dir` support `${env.VAR}` syntax to reference environment variables:
  468. ```toml
  469. [filters]
  470. dir = "${env.HOME}/.config/snip/filters"
  471. [tracking]
  472. db_path = "${env.XDG_DATA_HOME}/snip/tracking.db"
  473. ```
  474. Tilde expansion (`~/`) is also supported and applied after env var expansion.
  475. ### Runner Prefixes
  476. When a command is run through a runner wrapper, snip strips the wrapper, applies the inner command's filter, and leaves the wrapper in place. So `uv run pytest` is filtered by the `pytest` filter with no extra configuration -- no need to copy or duplicate the filter.
  477. ```bash
  478. uv run pytest -v # filtered by the pytest filter
  479. uv run --python 3.12 pytest # runner flags before the command are skipped
  480. poetry run ruff check . # filtered by the ruff filter
  481. ```
  482. Built-in prefixes: `uv run`, `poetry run`, `pdm run`, `pipenv run`, `rye run`, `hatch run`, and the shell wrappers `noglob`, `nocorrect`, `command`, `exec`. Add your own (e.g. a container or env wrapper) with `transparent_prefixes`:
  483. ```toml
  484. [filters]
  485. transparent_prefixes = ["docker exec mycontainer", "direnv exec ."]
  486. ```
  487. Detection is fail-closed: the first non-flag token after the prefix must be a known snip command, otherwise the command passes through untouched. A runner executing an unknown program (e.g. `uv run bash -c ...`) is never rewritten and never auto-allowed, preserving snip's confirmation-prompt guarantee.
  488. ## Design
  489. - **Startup < 10ms** — snip intercepts every shell command; latency is critical
  490. - **Graceful degradation** — if a filter fails, fall back to raw output
  491. - **Exit code preservation** — always propagate the underlying tool's exit code
  492. - **Lazy regex compilation** — `sync.Once` per pattern, reused across invocations
  493. - **Zero CGO** — pure Go SQLite driver, static binaries, trivial cross-compilation
  494. - **Goroutine concurrency** — stdout/stderr captured in parallel without thread pools
  495. ## Design Philosophy
  496. snip chose a fundamentally different approach to LLM token reduction: **filters are data, not code**. The binary is the engine, filters are YAML data files, and the two evolve independently.
  497. | | **[rtk](https://github.com/rtk-ai/rtk)** (Rust) | **snip** (Go) |
  498. |---|---|---|
  499. | Filter authoring | Write Rust, recompile, wait for release | Write YAML, drop in a folder, done |
  500. | Filter format | Compiled into the binary | Declarative YAML, engine and filters evolve independently |
  501. | Custom filters | Fork the repo, add Rust code | Create a `.yaml` file in `~/.config/snip/filters/` |
  502. | Concurrency | 2 OS threads | Goroutines (lightweight, no thread pool) |
  503. | SQLite | Requires CGO + C compiler | Pure Go driver, static binary, no dependencies |
  504. | Cross-compilation | Per-target C toolchain | `GOOS=linux GOARCH=arm64 go build` |
  505. | Pipeline actions | Built-in strategies | 20 composable actions (keep, remove, regex, JSON, state machine...) |
  506. | Contributing | Rust knowledge required | YAML knowledge sufficient |
  507. Both tools solve the same problem: reducing AI token costs from verbose CLI output. snip's bet is that **extensibility wins**. When anyone can write a filter in 5 minutes without touching Go or Rust, the filter ecosystem grows faster.
  508. ## Development
  509. ```bash
  510. make build # static binary (CGO_ENABLED=0)
  511. make build-lite # build without SQLite tracking (-tags lite, ~5MB smaller)
  512. make test # all tests with coverage
  513. make test-race # race detector
  514. make verify # run the filters' inline tests
  515. make lint # go vet + golangci-lint (pinned version)
  516. make vulncheck # govulncheck ./...
  517. make ci # pre-PR gate: test-race + verify + lint + vulncheck
  518. make install # install using GOBIN or the Go environment
  519. make upgrade # replace the active snip binary (GOBIN overrides)
  520. ```
  521. ## Documentation
  522. Full documentation is available on the **[Wiki](https://github.com/edouard-claude/snip/wiki)**:
  523. - [Installation](https://github.com/edouard-claude/snip/wiki/Installation) — Homebrew, Go, binaries (macOS/Linux/Windows), from source
  524. - [Integration](https://github.com/edouard-claude/snip/wiki/Integration) — Claude Code, Cursor, Copilot, Gemini, Kilo Code, Antigravity, and more
  525. - [Gain Dashboard](https://github.com/edouard-claude/snip/wiki/Gain-Dashboard) — Token savings reports and analytics
  526. - [Learn](https://github.com/edouard-claude/snip/wiki/Learn) — Detect CLI error-correction patterns, generate agent rules
  527. - [Filters](https://github.com/edouard-claude/snip/wiki/Filters) — Built-in filters, custom filters
  528. - [Filter DSL Reference](https://github.com/edouard-claude/snip/wiki/Filter-DSL-Reference) — All 20 pipeline actions
  529. - [Configuration](https://github.com/edouard-claude/snip/wiki/Configuration) — TOML config, environment variables
  530. - [Architecture](https://github.com/edouard-claude/snip/wiki/Architecture) — Design decisions, internals
  531. - [Contributing](https://github.com/edouard-claude/snip/wiki/Contributing) — Dev setup, adding filters, conventions
  532. ## Credits
  533. Inspired by [rtk](https://github.com/rtk-ai/rtk) (Rust Token Killer) by the rtk-ai team. rtk proved that filtering shell output before it reaches the LLM context window is a powerful idea for cutting AI coding costs. snip rebuilds the concept in Go with a focus on extensibility -- declarative YAML filters that anyone can write without touching the codebase.
  534. ## License
  535. MIT
install.sh · Bundled script · 127 lines · 1 finding marked
  1. #!/bin/sh
  2. # install.sh - Install snip (LLM token optimizer)
  3. # Usage: curl -fsSL https://raw.githubusercontent.com/edouard-claude/snip/master/install.sh | sh
    • Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
    • Line 3 on GitHub
  4. set -e
  5. REPO="edouard-claude/snip"
  6. INSTALL_DIR="/usr/local/bin"
  7. FALLBACK_DIR="${HOME}/.local/bin"
  8. # --- helpers ---
  9. info() {
  10. printf '[snip] %s\n' "$1"
  11. }
  12. error() {
  13. printf '[snip] ERROR: %s\n' "$1" >&2
  14. exit 1
  15. }
  16. need_cmd() {
  17. if ! command -v "$1" > /dev/null 2>&1; then
  18. error "required command not found: $1"
  19. fi
  20. }
  21. # --- detect platform ---
  22. detect_os() {
  23. case "$(uname -s)" in
  24. Linux*) echo "linux" ;;
  25. Darwin*) echo "darwin" ;;
  26. *) error "unsupported OS: $(uname -s)" ;;
  27. esac
  28. }
  29. detect_arch() {
  30. case "$(uname -m)" in
  31. x86_64|amd64) echo "amd64" ;;
  32. aarch64|arm64) echo "arm64" ;;
  33. *) error "unsupported architecture: $(uname -m)" ;;
  34. esac
  35. }
  36. # --- main ---
  37. main() {
  38. need_cmd curl
  39. need_cmd tar
  40. need_cmd uname
  41. OS="$(detect_os)"
  42. ARCH="$(detect_arch)"
  43. info "detected platform: ${OS}/${ARCH}"
  44. # fetch latest version
  45. info "fetching latest release..."
  46. LATEST_TAG=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" \
  47. | grep '"tag_name"' \
  48. | head -1 \
  49. | sed 's/.*"tag_name": *"//;s/".*//')
  50. if [ -z "${LATEST_TAG}" ]; then
  51. error "could not determine latest release"
  52. fi
  53. VERSION="${LATEST_TAG#v}"
  54. info "latest version: ${VERSION} (${LATEST_TAG})"
  55. # build download URL
  56. # GoReleaser template: snip_<version>_<os>_<arch>.tar.gz
  57. ARCHIVE="snip_${VERSION}_${OS}_${ARCH}.tar.gz"
  58. URL="https://github.com/${REPO}/releases/download/${LATEST_TAG}/${ARCHIVE}"
  59. # create temp directory
  60. TMP_DIR="$(mktemp -d)"
  61. trap 'rm -rf "${TMP_DIR}"' EXIT
  62. # download
  63. info "downloading ${URL}"
  64. curl -fsSL -o "${TMP_DIR}/${ARCHIVE}" "${URL}"
  65. # extract
  66. info "extracting..."
  67. tar xzf "${TMP_DIR}/${ARCHIVE}" -C "${TMP_DIR}"
  68. if [ ! -f "${TMP_DIR}/snip" ]; then
  69. error "binary not found in archive"
  70. fi
  71. # install
  72. if [ -d "${INSTALL_DIR}" ] && [ -w "${INSTALL_DIR}" ]; then
  73. TARGET="${INSTALL_DIR}/snip"
  74. else
  75. mkdir -p "${FALLBACK_DIR}"
  76. TARGET="${FALLBACK_DIR}/snip"
  77. info "${INSTALL_DIR} is not writable, installing to ${FALLBACK_DIR}"
  78. fi
  79. mv "${TMP_DIR}/snip" "${TARGET}"
  80. chmod +x "${TARGET}"
  81. # verify
  82. if ! "${TARGET}" --version > /dev/null 2>&1; then
  83. info "installed to ${TARGET}"
  84. else
  85. INSTALLED_VERSION="$("${TARGET}" --version 2>&1 || true)"
  86. info "installed ${INSTALLED_VERSION} to ${TARGET}"
  87. fi
  88. # check PATH
  89. case ":${PATH}:" in
  90. *":$(dirname "${TARGET}"):"*) ;;
  91. *)
  92. printf '\n'
  93. info "WARNING: $(dirname "${TARGET}") is not in your PATH"
  94. info "Add it with: export PATH=\"$(dirname "${TARGET}"):\${PATH}\""
  95. ;;
  96. esac
  97. printf '\n'
  98. info "done! Run 'snip init' to set up your AI coding assistant hook."
  99. }
  100. main

Ratings and comments

Sign in to rate this skill.

Sign in

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