Skip to main content

lean_ctx_ext/
rewrite_registry.rs

1// SPDX-License-Identifier: Apache-2.0
2/// Single source of truth for all commands that lean-ctx rewrites/compresses.
3/// Used by: hook_handlers (PreToolUse), hooks.rs (bash scripts), cli.rs (shell aliases).
4pub const REWRITE_COMMANDS: &[RewriteEntry] = &[
5    // Version control
6    re("git", Category::Vcs),
7    re("gh", Category::Vcs),
8    // Rust
9    re("cargo", Category::Build),
10    // JavaScript/Node
11    re("npm", Category::PackageManager),
12    re("pnpm", Category::PackageManager),
13    re("yarn", Category::PackageManager),
14    re("bun", Category::Build),
15    re("bunx", Category::Build),
16    re("deno", Category::Build),
17    re("vite", Category::Build),
18    // Python
19    re("python", Category::Build),
20    re("python3", Category::Build),
21    re("pip", Category::PackageManager),
22    re("pip3", Category::PackageManager),
23    re("uv", Category::PackageManager),
24    re("pytest", Category::Build),
25    re("mypy", Category::Lint),
26    re("ruff", Category::Lint),
27    // Go
28    re("go", Category::Build),
29    re("golangci-lint", Category::Lint),
30    // Containers / Infra
31    re("docker", Category::Infra),
32    re("docker-compose", Category::Infra),
33    re("kubectl", Category::Infra),
34    re("helm", Category::Infra),
35    re("aws", Category::Infra),
36    re("terraform", Category::Infra),
37    re("tofu", Category::Infra),
38    // Linters / Formatters
39    re("eslint", Category::Lint),
40    re("prettier", Category::Lint),
41    re("tsc", Category::Lint),
42    re("biome", Category::Lint),
43    // HTTP
44    re("curl", Category::Http),
45    re("wget", Category::Http),
46    // PHP
47    re("php", Category::Build),
48    re("composer", Category::PackageManager),
49    // .NET
50    re("dotnet", Category::Build),
51    // Ruby
52    re("bundle", Category::PackageManager),
53    re("rake", Category::Build),
54    // Elixir
55    re("mix", Category::Build),
56    // Swift / Zig / CMake
57    re("swift", Category::Build),
58    re("zig", Category::Build),
59    re("cmake", Category::Build),
60    re("make", Category::Build),
61    // Search (rewritten in hooks to enforce hybrid)
62    re("grep", Category::Search),
63    re("egrep", Category::Search),
64    re("fgrep", Category::Search),
65    re("rg", Category::Search),
66    // File read alternatives (rewritten to lean-ctx read, not lean-ctx -c)
67    re("cat", Category::FileRead),
68    re("head", Category::FileRead),
69    re("tail", Category::FileRead),
70    // Directory listing (rewritten in hooks to enforce hybrid; may fall back to `lean-ctx -c`)
71    re("ls", Category::DirList),
72    re("find", Category::DirList),
73];
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76pub enum Category {
77    Vcs,
78    Build,
79    PackageManager,
80    Lint,
81    Infra,
82    Http,
83    Search,
84    FileRead,
85    DirList,
86}
87
88#[derive(Debug, Clone, Copy)]
89pub struct RewriteEntry {
90    pub command: &'static str,
91    pub category: Category,
92}
93
94const fn re(command: &'static str, category: Category) -> RewriteEntry {
95    RewriteEntry { command, category }
96}
97
98/// Commands eligible for PreToolUse hook rewriting (IDE hooks).
99/// Excludes `FileRead` (handled separately in hook_handlers).
100pub fn hook_prefixes() -> Vec<String> {
101    REWRITE_COMMANDS
102        .iter()
103        .filter(|e| !matches!(e.category, Category::FileRead))
104        .map(|e| format!("{} ", e.command))
105        .collect()
106}
107
108/// Commands eligible for PreToolUse hook (bare command match, no trailing space).
109/// Used for commands like `eslint`, `prettier`, `tsc` that may run without args.
110pub fn hook_bare_commands() -> Vec<&'static str> {
111    REWRITE_COMMANDS
112        .iter()
113        .filter(|e| !matches!(e.category, Category::FileRead))
114        .map(|e| e.command)
115        .collect()
116}
117
118/// Check if a command is a file-read alternative (cat/head/tail) that should be
119/// rewritten to `lean-ctx read` rather than `lean-ctx -c`.
120pub fn is_file_read_command(cmd: &str) -> bool {
121    REWRITE_COMMANDS
122        .iter()
123        .filter(|e| e.category == Category::FileRead)
124        .any(|e| {
125            let prefix = format!("{} ", e.command);
126            cmd.starts_with(&prefix) || cmd == e.command
127        })
128}
129
130/// All command names for shell alias generation.
131pub fn shell_alias_commands() -> Vec<&'static str> {
132    REWRITE_COMMANDS.iter().map(|e| e.command).collect()
133}
134
135/// Generates a bash `case` pattern for rewrite scripts.
136/// e.g. `git\ *|gh\ *|cargo\ *|npm\ *|...`
137pub fn bash_case_pattern() -> String {
138    REWRITE_COMMANDS
139        .iter()
140        .filter(|e| !matches!(e.category, Category::FileRead))
141        .map(|e| {
142            if e.command.contains('-') {
143                format!("{}*", e.command.replace('-', r"\-"))
144            } else {
145                format!(r"{}\ *", e.command)
146            }
147        })
148        .collect::<Vec<_>>()
149        .join("|")
150}
151
152/// Space-separated list for shell alias arrays.
153pub fn shell_alias_list() -> String {
154    shell_alias_commands().join(" ")
155}
156
157/// Check if a command string matches a rewritable prefix (for hook handlers).
158/// Excludes FileRead (handled separately in hook_handlers).
159///
160/// Handles common shell patterns:
161/// - Bare command: `git status`
162/// - Env-var prefixed: `PYTHONPATH=src python script.py`
163/// - Path-qualified: `./.venv/bin/python`, `/usr/bin/python3`
164pub fn is_rewritable_command(cmd: &str) -> bool {
165    let effective = strip_env_prefix(cmd);
166    let basename = extract_command_basename(effective);
167
168    for entry in REWRITE_COMMANDS {
169        if matches!(entry.category, Category::FileRead) {
170            continue;
171        }
172        let prefix = format!("{} ", entry.command);
173        if effective.starts_with(&prefix)
174            || effective == entry.command
175            || basename == entry.command
176            || basename.starts_with(&format!("{} ", entry.command))
177        {
178            return true;
179        }
180    }
181    false
182}
183
184/// Strip leading `KEY=value` env-var assignments from a command string.
185/// e.g. `PYTHONPATH=src FOO=bar python x.py` → `python x.py`
186pub fn strip_env_prefix(cmd: &str) -> &str {
187    let mut rest = cmd;
188    loop {
189        let trimmed = rest.trim_start();
190        if let Some(eq_pos) = trimmed.find('=') {
191            let before_eq = &trimmed[..eq_pos];
192            if !before_eq.is_empty()
193                && before_eq
194                    .bytes()
195                    .all(|b| b.is_ascii_alphanumeric() || b == b'_')
196                && let Some(space_pos) = trimmed[eq_pos..].find(' ')
197            {
198                rest = &trimmed[eq_pos + space_pos..];
199                continue;
200            }
201        }
202        return trimmed;
203    }
204}
205
206/// Extract the basename of a potentially path-qualified command.
207/// e.g. `./.venv/bin/python script.py` → `python script.py`
208///      `/usr/local/bin/cargo test` → `cargo test`
209fn extract_command_basename(cmd: &str) -> &str {
210    let first_space = cmd.find(' ').unwrap_or(cmd.len());
211    let cmd_part = &cmd[..first_space];
212    if let Some(slash_pos) = cmd_part.rfind('/') {
213        &cmd[slash_pos + 1..]
214    } else {
215        cmd
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn no_duplicates() {
225        let mut seen = std::collections::HashSet::new();
226        for entry in REWRITE_COMMANDS {
227            assert!(
228                seen.insert(entry.command),
229                "duplicate command: {}",
230                entry.command
231            );
232        }
233    }
234
235    #[test]
236    fn hook_prefixes_exclude_search_fileread_dirlist() {
237        let prefixes = hook_prefixes();
238        assert!(!prefixes.contains(&"cat ".to_string()));
239        assert!(!prefixes.contains(&"head ".to_string()));
240        assert!(!prefixes.contains(&"tail ".to_string()));
241        assert!(prefixes.contains(&"rg ".to_string()));
242        assert!(prefixes.contains(&"grep ".to_string()));
243        assert!(prefixes.contains(&"egrep ".to_string()));
244        assert!(prefixes.contains(&"fgrep ".to_string()));
245        assert!(prefixes.contains(&"ls ".to_string()));
246        assert!(prefixes.contains(&"find ".to_string()));
247        assert!(prefixes.contains(&"git ".to_string()));
248        assert!(prefixes.contains(&"cargo ".to_string()));
249    }
250
251    #[test]
252    fn is_rewritable_matches() {
253        assert!(is_rewritable_command("git status"));
254        assert!(is_rewritable_command("cargo test --lib"));
255        assert!(is_rewritable_command("npm run build"));
256        assert!(is_rewritable_command("eslint"));
257        assert!(is_rewritable_command("docker-compose up"));
258        assert!(is_rewritable_command("bun install"));
259        assert!(is_rewritable_command("bunx vitest"));
260        assert!(is_rewritable_command("deno test"));
261        assert!(is_rewritable_command("vite build"));
262        assert!(is_rewritable_command("terraform plan"));
263        assert!(is_rewritable_command("make build"));
264        assert!(is_rewritable_command("dotnet build"));
265        assert!(is_rewritable_command("python script.py"));
266        assert!(is_rewritable_command("python3 -m pytest"));
267        assert!(is_rewritable_command("uv run test"));
268    }
269
270    #[test]
271    fn is_rewritable_env_prefix() {
272        assert!(is_rewritable_command("PYTHONPATH=src python script.py"));
273        assert!(is_rewritable_command("FOO=bar BAZ=1 cargo test"));
274        assert!(is_rewritable_command("NODE_ENV=test npm run test"));
275        assert!(!is_rewritable_command("FOO=bar echo hello"));
276    }
277
278    #[test]
279    fn is_rewritable_path_qualified() {
280        assert!(is_rewritable_command("./.venv/bin/python script.py"));
281        assert!(is_rewritable_command("/usr/bin/python3 test.py"));
282        assert!(is_rewritable_command("/usr/local/bin/cargo build"));
283        assert!(is_rewritable_command(
284            "PYTHONPATH=src ./.venv/bin/python script.py"
285        ));
286        assert!(!is_rewritable_command("/usr/bin/some-unknown-tool arg"));
287    }
288
289    #[test]
290    fn is_rewritable_excludes() {
291        assert!(!is_rewritable_command("echo hello"));
292        assert!(!is_rewritable_command("cd src"));
293        assert!(!is_rewritable_command("cat file.rs"));
294        assert!(!is_rewritable_command("head -20 file.rs"));
295        assert!(is_rewritable_command("rg pattern"));
296        assert!(is_rewritable_command("grep -rn pattern src/"));
297        assert!(is_rewritable_command("egrep 'foo|bar' file.rs"));
298        assert!(is_rewritable_command("fgrep literal file.rs"));
299        assert!(is_rewritable_command("ls /tmp"));
300        assert!(is_rewritable_command("find . -name '*.rs'"));
301    }
302
303    #[test]
304    fn strip_env_prefix_works() {
305        assert_eq!(strip_env_prefix("python x.py"), "python x.py");
306        assert_eq!(strip_env_prefix("FOO=bar python x.py"), "python x.py");
307        assert_eq!(strip_env_prefix("A=1 B=2 cargo test"), "cargo test");
308        assert_eq!(strip_env_prefix("  FOO=bar cmd"), "cmd");
309        assert_eq!(strip_env_prefix("no_equals here"), "no_equals here");
310    }
311
312    #[test]
313    fn extract_command_basename_works() {
314        assert_eq!(extract_command_basename("python x.py"), "python x.py");
315        assert_eq!(
316            extract_command_basename("./.venv/bin/python x.py"),
317            "python x.py"
318        );
319        assert_eq!(
320            extract_command_basename("/usr/bin/python3 -m pytest"),
321            "python3 -m pytest"
322        );
323        assert_eq!(extract_command_basename("cargo test"), "cargo test");
324    }
325
326    #[test]
327    fn file_read_commands_detected() {
328        assert!(is_file_read_command("cat file.rs"));
329        assert!(is_file_read_command("head -20 file.rs"));
330        assert!(is_file_read_command("tail -n 10 file.rs"));
331        assert!(!is_file_read_command("git status"));
332        assert!(!is_file_read_command("echo hello"));
333    }
334
335    #[test]
336    fn shell_alias_list_includes_all() {
337        let list = shell_alias_list();
338        assert!(list.contains("git"));
339        assert!(list.contains("cargo"));
340        assert!(list.contains("docker-compose"));
341        assert!(list.contains("rg"));
342        assert!(list.contains(" ls ") || list.ends_with(" ls"));
343        assert!(list.contains("find"));
344    }
345
346    #[test]
347    fn bash_case_pattern_valid() {
348        let pattern = bash_case_pattern();
349        assert!(pattern.contains(r"git\ *"));
350        assert!(pattern.contains(r"cargo\ *"));
351        assert!(pattern.contains(r"rg\ *"));
352        assert!(pattern.contains(r"ls\ *"));
353    }
354
355    #[test]
356    fn hook_prefixes_superset_of_bare_commands() {
357        let prefixes = hook_prefixes();
358        let bare = hook_bare_commands();
359        for cmd in &bare {
360            let with_space = format!("{cmd} ");
361            assert!(
362                prefixes.contains(&with_space),
363                "bare command '{cmd}' missing from hook_prefixes"
364            );
365        }
366        assert!(
367            !bare.contains(&"cat"),
368            "FileRead commands must not be in hook_bare_commands"
369        );
370    }
371
372    #[test]
373    fn shell_aliases_superset_of_hook_commands() {
374        let aliases = shell_alias_commands();
375        let hook = hook_bare_commands();
376        for cmd in &hook {
377            assert!(
378                aliases.contains(cmd),
379                "hook command '{cmd}' missing from shell_alias_commands"
380            );
381        }
382    }
383
384    #[test]
385    fn all_categories_represented() {
386        let categories: std::collections::HashSet<_> =
387            REWRITE_COMMANDS.iter().map(|e| e.category).collect();
388        assert!(categories.contains(&Category::Vcs));
389        assert!(categories.contains(&Category::Build));
390        assert!(categories.contains(&Category::PackageManager));
391        assert!(categories.contains(&Category::Lint));
392        assert!(categories.contains(&Category::Infra));
393        assert!(categories.contains(&Category::Http));
394        assert!(categories.contains(&Category::Search));
395        assert!(categories.contains(&Category::DirList));
396    }
397
398    #[test]
399    fn every_command_rewritable_except_fileread() {
400        for entry in REWRITE_COMMANDS {
401            let cmd = format!("{} --version", entry.command);
402            if matches!(entry.category, Category::FileRead) {
403                assert!(
404                    !is_rewritable_command(&cmd),
405                    "{:?} command '{}' should NOT be rewritable via -c wrap",
406                    entry.category,
407                    entry.command
408                );
409            } else {
410                assert!(
411                    is_rewritable_command(&cmd),
412                    "command '{}' should be rewritable",
413                    entry.command
414                );
415            }
416        }
417    }
418
419    #[test]
420    fn bash_pattern_has_entry_for_every_hookable_command() {
421        let pattern = bash_case_pattern();
422        for entry in REWRITE_COMMANDS {
423            if matches!(entry.category, Category::FileRead) {
424                continue;
425            }
426            let escaped = if entry.command.contains('-') {
427                format!("{}*", entry.command.replace('-', r"\-"))
428            } else {
429                format!(r"{}\ *", entry.command)
430            };
431            assert!(
432                pattern.contains(&escaped),
433                "bash case pattern missing '{}'",
434                entry.command
435            );
436        }
437    }
438}