Skip to content

Commit

Permalink
feat: Add staticPrefix function.
Browse files Browse the repository at this point in the history
  • Loading branch information
erikgeiser committed Nov 6, 2020
1 parent 7cc372f commit 5f4934a
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 0 deletions.
55 changes: 55 additions & 0 deletions prefix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package zglob

import (
"fmt"
"path"
"path/filepath"
"strings"

"github.com/gobwas/glob/syntax/ast"
"github.com/gobwas/glob/syntax/lexer"
)

func staticPrefix(pattern string) (string, error) {
parts := strings.Split(pattern, string(filepath.Separator))

prefix := ""
if len(pattern) > 0 && pattern[0] == filepath.Separator {
prefix = string(filepath.Separator)
}

for _, part := range parts {
if part == "" {
continue
}

rootNode, err := ast.Parse(lexer.NewLexer(part))
if err != nil {
return "", fmt.Errorf("parse glob pattern: %w", err)
}

nChildren := len(rootNode.Children)

if nChildren > 1 {
break
}

candidate := rootNode
if len(rootNode.Children) == 1 {
candidate = rootNode.Children[0]
}

v, ok := candidate.Value.(ast.Text)
if !ok {
break
}

prefix = path.Join(prefix, v.Text)
}

if prefix == "" {
prefix = "."
}

return prefix, nil
}
29 changes: 29 additions & 0 deletions prefix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package zglob

import "testing"

func TestStaticPrefix(t *testing.T) {
var testCases = []struct {
pattern string
prefix string
}{
{"/foo/b*ar/baz", "/foo"},
{"foo/bar", "foo/bar"},
{"/foo/bar/{b,p}az", "/foo/bar"},
{"*/foo", "."},
{"./", "."},
{"fo\\*o/bar/b*z", "fo*o/bar"},
{"/\\{foo\\}/bar", "/{foo}/bar"},
}

for _, testCase := range testCases {
prefix, err := staticPrefix(testCase.pattern)
if err != nil {
t.Errorf("staticPrefix: %v", err)
}
if prefix != testCase.prefix {
t.Errorf("prefixPrefix returned %q instead of %q for pattern %q",
prefix, testCase.prefix, testCase.pattern)
}
}
}

0 comments on commit 5f4934a

Please sign in to comment.