File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -2,16 +2,18 @@ import { sortBy, pipe } from "remeda"
22
33export namespace Wildcard {
44 export function match ( str : string , pattern : string ) {
5- const regex = new RegExp (
6- "^" +
7- pattern
8- . replace ( / [ . + ^ $ { } ( ) | [ \] \\ ] / g, "\\$&" ) // escape special regex chars
9- . replace ( / \* / g, ".*" ) // * becomes .*
10- . replace ( / \? / g, "." ) + // ? becomes .
11- "$" ,
12- "s" , // s flag enables multiline matching
13- )
14- return regex . test ( str )
5+ let escaped = pattern
6+ . replace ( / [ . + ^ $ { } ( ) | [ \] \\ ] / g, "\\$&" ) // escape special regex chars
7+ . replace ( / \* / g, ".*" ) // * becomes .*
8+ . replace ( / \? / g, "." ) // ? becomes .
9+
10+ // If pattern ends with " *" (space + wildcard), make the trailing part optional
11+ // This allows "ls *" to match both "ls" and "ls -la"
12+ if ( escaped . endsWith ( " .*" ) ) {
13+ escaped = escaped . slice ( 0 , - 3 ) + "( .*)?"
14+ }
15+
16+ return new RegExp ( "^" + escaped + "$" , "s" ) . test ( str )
1517 }
1618
1719 export function all ( input : string , patterns : Record < string , any > ) {
Original file line number Diff line number Diff line change @@ -7,6 +7,26 @@ test("match handles glob tokens", () => {
77 expect ( Wildcard . match ( "foo+bar" , "foo+bar" ) ) . toBe ( true )
88} )
99
10+ test ( "match with trailing space+wildcard matches command with or without args" , ( ) => {
11+ // "ls *" should match "ls" (no args) and "ls -la" (with args)
12+ expect ( Wildcard . match ( "ls" , "ls *" ) ) . toBe ( true )
13+ expect ( Wildcard . match ( "ls -la" , "ls *" ) ) . toBe ( true )
14+ expect ( Wildcard . match ( "ls foo bar" , "ls *" ) ) . toBe ( true )
15+
16+ // "ls*" (no space) should NOT match "ls" alone — wait, it should because .* matches empty
17+ // but it WILL match "lstmeval" which is the dangerous case users should avoid
18+ expect ( Wildcard . match ( "ls" , "ls*" ) ) . toBe ( true )
19+ expect ( Wildcard . match ( "lstmeval" , "ls*" ) ) . toBe ( true )
20+
21+ // "ls *" (with space) should NOT match "lstmeval"
22+ expect ( Wildcard . match ( "lstmeval" , "ls *" ) ) . toBe ( false )
23+
24+ // multi-word commands
25+ expect ( Wildcard . match ( "git status" , "git *" ) ) . toBe ( true )
26+ expect ( Wildcard . match ( "git" , "git *" ) ) . toBe ( true )
27+ expect ( Wildcard . match ( "git commit -m foo" , "git *" ) ) . toBe ( true )
28+ } )
29+
1030test ( "all picks the most specific pattern" , ( ) => {
1131 const rules = {
1232 "*" : "deny" ,
You can’t perform that action at this time.
0 commit comments