summary refs log tree commit diff
path: root/vendor/go.mau.fi/util/glob/util.go
diff options
context:
space:
mode:
authorEmile <git@emile.space>2024-10-25 15:55:50 +0200
committerEmile <git@emile.space>2024-10-25 15:55:50 +0200
commitc90f36e3dd179d2de96f4f5fe38d8dc9a9de6dfe (patch)
tree89e9afb41c5bf76f48cfb09305a2d3db8d302b06 /vendor/go.mau.fi/util/glob/util.go
parent98bbb0f559a8883bc47bae80607dbe326a448e61 (diff)
vendor HEAD main
Diffstat (limited to 'vendor/go.mau.fi/util/glob/util.go')
-rw-r--r--vendor/go.mau.fi/util/glob/util.go42
1 files changed, 42 insertions, 0 deletions
diff --git a/vendor/go.mau.fi/util/glob/util.go b/vendor/go.mau.fi/util/glob/util.go
new file mode 100644
index 0000000..37d9b2d
--- /dev/null
+++ b/vendor/go.mau.fi/util/glob/util.go
@@ -0,0 +1,42 @@
+package glob
+
+import (
+	"regexp"
+	"strings"
+)
+
+var redundantStarRegex = regexp.MustCompile(`\*{2,}`)
+var maybeRedundantQuestionRegex = regexp.MustCompile(`[*?]{2,}`)
+var wildcardRegex = regexp.MustCompile(`[*?]+`)
+
+func SplitPattern(pattern string) []string {
+	indexes := wildcardRegex.FindAllStringIndex(pattern, -1)
+	if len(indexes) == 0 {
+		return []string{pattern}
+	}
+	parts := make([]string, 0, len(indexes)+1)
+	start := 0
+	for _, part := range indexes {
+		end := part[0]
+		if end > start {
+			parts = append(parts, pattern[start:end])
+		}
+		parts = append(parts, pattern[part[0]:part[1]])
+		start = part[1]
+	}
+	if start < len(pattern) {
+		parts = append(parts, pattern[start:])
+	}
+	return parts
+}
+
+func Simplify(pattern string) string {
+	pattern = redundantStarRegex.ReplaceAllString(pattern, "*")
+	pattern = maybeRedundantQuestionRegex.ReplaceAllStringFunc(pattern, func(s string) string {
+		if !strings.ContainsRune(s, '*') {
+			return s
+		}
+		return strings.Repeat("?", strings.Count(s, "?")) + "*"
+	})
+	return pattern
+}