| 1 | package permission |
| 2 | |
| 3 | import "reasonix/internal/shellparse" |
| 4 | |
| 5 | // DecomposeBashCommand splits a compound bash command line into its |
| 6 | // simple-command segments so each segment can be matched against the rule |
| 7 | // table independently. This is the mechanism Claude Code and comparable |
| 8 | // harnesses use to make prefix rules like `Bash(git push:*)` reusable across |
| 9 | // compound invocations without ever synthesizing a new prefix from a compound |
| 10 | // command. |
| 11 | // |
| 12 | // It splits on the shell control operators `;`, `&`, `&&`, `|`, `||`, and |
| 13 | // newlines. Quoting (single, double, backslash-escapes inside double quotes) |
| 14 | // and $(...) / <(...) / >(...) / `...` command / process substitutions are |
| 15 | // treated as opaque — operators inside them do NOT split the outer command. |
| 16 | // File-descriptor duplication like `2>&1` and combined redirects like |
| 17 | // `&>/dev/null` are recognized as redirection syntax rather than splitters. |
| 18 | // |
| 19 | // Known out-of-scope shapes — the parser refuses to decompose these to keep |
| 20 | // downstream matching safe, so callers fall back to whole-string matching: |
| 21 | // - heredocs (`cat <<EOF … EOF`): the delimiter body isn't shell syntax, |
| 22 | // but tokenizing it as one is wrong. |
| 23 | // - leading operator (`&& ls`, `; ls`): malformed shell. |
| 24 | // - unbalanced quotes and unsupported compound statements. |
| 25 | // |
| 26 | // Returns nil when the input has no control operator to split on, or when the |
| 27 | // parser encounters one of the above out-of-scope shapes. Redirect fragments |
| 28 | // (`2>/dev/null`, `> file`) are left attached to the simple command they |
| 29 | // annotate; permission matching later strips only the conservative safe subset. |
| 30 | // |
| 31 | // The only contract this function exposes is `[]string` of trimmed |
| 32 | // simple-command text, or `nil` for "fall back to exact match". |
| 33 | func DecomposeBashCommand(cmd string) []string { |
| 34 | out, split, ok := shellparse.SplitTopLevel(cmd) |
| 35 | if !ok || !split || len(out) < 2 { |
| 36 | return nil |
| 37 | } |
| 38 | return out |
| 39 | } |
| 40 |