-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuzzy.go
More file actions
321 lines (272 loc) · 7.81 KB
/
Copy pathfuzzy.go
File metadata and controls
321 lines (272 loc) · 7.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
// Package fuzzy - Entry point for fuzzy searching
package fuzzy
import (
"fmt"
"math"
"runtime"
"sort"
"strings"
"sync"
"github.com/versenilvis/fuzzy/core"
)
// SearchOptions provides advanced search configuration
type SearchOptions struct {
ContextBoosts map[string]int // Optional boosts for specific items
Limit int // Maximum number of results to return
}
// MatchResult represents a scored search result
type MatchResult struct {
Str string
Score int
}
// Searcher is the main object for performing fuzzy searches
type Searcher struct {
Originals []string // Original items
Normalized [][]byte // Normalized items for fast matching
Memory *core.FileMemory // Frecency memory system
Filter *core.UnigramFilter // Bitset filter for candidates
baseStarts []int // Start indices of filenames in paths
scorePool *sync.Pool // Pool for reusing score buffers
}
// NewPlainSearcher creates a searcher for plain text items
func NewPlainSearcher(items []string) *Searcher {
numItems := len(items)
originals := make([]string, numItems)
normPaths := make([][]byte, numItems)
baseStarts := make([]int, numItems)
for i, item := range items {
originals[i] = item
normItem := core.Normalize(item)
baseStarts[i] = len(normItem)
normPaths[i] = []byte(normItem)
}
return &Searcher{
Originals: originals,
Normalized: normPaths,
Memory: core.NewFileMemory(nil),
Filter: core.NewUnigramFilter(normPaths),
baseStarts: baseStarts,
scorePool: &sync.Pool{
New: func() any {
buf := make([]int, numItems)
for i := range buf {
buf[i] = math.MinInt
}
return &buf
},
},
}
}
// NewSearcher creates a searcher optimized for file paths
func NewSearcher(items []string) *Searcher {
numItems := len(items)
originals := make([]string, numItems)
normPaths := make([][]byte, numItems)
baseStarts := make([]int, numItems)
for i, item := range items {
originals[i] = item
bStart := -1
for j := len(item) - 1; j >= 0; j-- {
if item[j] == '/' || item[j] == '\\' {
bStart = j + 1
break
}
}
if bStart != -1 && bStart < len(item) {
filename := item[bStart:]
normFilename := core.Normalize(filename)
baseStarts[i] = len(normFilename)
priorityString := filename + " " + item
normPaths[i] = []byte(core.Normalize(priorityString))
} else {
normItem := core.Normalize(item)
baseStarts[i] = len(normItem)
normPaths[i] = []byte(normItem)
}
}
return &Searcher{
Originals: originals,
Normalized: normPaths,
Memory: core.NewFileMemory(nil),
Filter: core.NewUnigramFilter(normPaths),
baseStarts: baseStarts,
scorePool: &sync.Pool{
New: func() any {
buf := make([]int, numItems)
for i := range buf {
buf[i] = math.MinInt
}
return &buf
},
},
}
}
// NewSearcherWithMemory creates a searcher with existing memory
func NewSearcherWithMemory(items []string, memory *core.FileMemory) *Searcher {
s := NewSearcher(items)
if memory != nil {
s.Memory = memory
}
return s
}
// SearchDebug prints debug information for a query
func (s *Searcher) SearchDebug(query string) {
fmt.Printf("DEBUG SEARCH Query: [%s]\n", query)
queryNorm := core.Normalize(query)
if queryNorm == "" {
return
}
queryPattern := []byte(queryNorm)
for i, item := range s.Originals {
score, matched := core.FuzzyScoreGreedy(queryPattern, s.Normalized[i], s.baseStarts[i])
fmt.Printf("Item: [%s] | Norm: [%s] | Score: %d | Matched: %v | baseStart: %d\n", item, string(s.Normalized[i]), score, matched, s.baseStarts[i])
}
}
// SearchWithScores performs fuzzy search and returns scored results
func (s *Searcher) SearchWithScores(query string, opts ...*SearchOptions) []MatchResult {
query = strings.TrimSpace(query)
if query == "" {
return nil
}
queryNorm := core.Normalize(query)
if queryNorm == "" {
return nil
}
queryPattern := []byte(queryNorm)
resLimit := 20
if len(opts) > 0 && opts[0] != nil && opts[0].Limit > 0 {
resLimit = opts[0].Limit
}
memoryBoosts := s.Memory.GetBoostScores(query)
var matches []core.FuzzyMatch
candidates := s.Filter.Filter(queryPattern)
if candidates != nil {
matches = core.FuzzyFindFiltered(queryPattern, s.Normalized, candidates, s.baseStarts, resLimit)
} else {
matches = core.FuzzyFindParallel(queryPattern, s.Normalized, s.baseStarts, s.Filter.Bin, resLimit)
}
if len(matches) == 0 && len(queryNorm) >= 3 {
matches = s.findButTypo(queryNorm)
}
if len(matches) == 0 {
return nil
}
scoreBufPtr := s.scorePool.Get().(*[]int)
scoreBuf := *scoreBufPtr
defer func() {
for i := range scoreBuf {
scoreBuf[i] = math.MinInt
}
s.scorePool.Put(scoreBufPtr)
}()
for _, m := range matches {
scoreBuf[m.Index] = m.Score
}
rankedResults := make([]MatchResult, 0, len(matches))
for _, m := range matches {
filePath := s.Originals[m.Index]
finalScore := m.Score
if boost, exists := memoryBoosts[filePath]; exists {
finalScore += boost
}
if len(opts) > 0 && opts[0] != nil && opts[0].ContextBoosts != nil {
if boost, exists := opts[0].ContextBoosts[filePath]; exists {
finalScore += boost
}
}
rankedResults = append(rankedResults, MatchResult{
Str: filePath,
Score: finalScore,
})
}
sort.Slice(rankedResults, func(i, j int) bool {
if rankedResults[i].Score == rankedResults[j].Score {
return rankedResults[i].Str < rankedResults[j].Str
}
return rankedResults[i].Score > rankedResults[j].Score
})
if len(rankedResults) < resLimit {
resLimit = len(rankedResults)
}
return rankedResults[:resLimit]
}
// Search performs fuzzy search and returns matching strings
func (s *Searcher) Search(query string, opts ...*SearchOptions) []string {
rankedResults := s.SearchWithScores(query, opts...)
if rankedResults == nil {
return nil
}
finalStrings := make([]string, len(rankedResults))
for i, res := range rankedResults {
finalStrings[i] = res.Str
}
return finalStrings
}
// findButTypo is a fallback search for typos using Levenshtein distance
func (s *Searcher) findButTypo(query string) []core.FuzzyMatch {
numItems := len(s.Normalized)
if numItems == 0 {
return nil
}
// allow 1 typo for every 4 characters in the query
threshold := max(len(query)/4, 1)
numCPUs := runtime.GOMAXPROCS(0)
chunkSize := (numItems + numCPUs - 1) / numCPUs
var wg sync.WaitGroup
resultChan := make(chan []core.FuzzyMatch, numCPUs)
// split work across all available CPU cores
for i := range numCPUs {
start := i * chunkSize
if start >= numItems {
break
}
end := min(start+chunkSize, numItems)
wg.Add(1)
go func(s0, e int) {
defer wg.Done()
var local []core.FuzzyMatch
for j := s0; j < e; j++ {
// skip if the item is marked as deleted in the tombstone bin
blockIdx := j / 64
bitPos := uint64(1) << (j % 64)
if blockIdx < len(s.Filter.Bin) && s.Filter.Bin[blockIdx]&bitPos != 0 {
continue
}
filename := string(s.Normalized[j][:s.baseStarts[j]])
dist := core.LevenshteinRatio(query, filename)
if dist <= threshold {
local = append(local, core.FuzzyMatch{
Index: j,
Score: 100 - dist*10,
})
}
}
resultChan <- local
}(start, end)
}
go func() {
wg.Wait()
close(resultChan)
}()
var matches []core.FuzzyMatch
for chunk := range resultChan {
matches = append(matches, chunk...)
}
return matches
}
// RecordSelection records an item selection to update frecency
func (s *Searcher) RecordSelection(query, filePath string) {
s.Memory.RecordSelection(query, filePath)
}
// ClearCache clears selection history
func (s *Searcher) ClearCache() {
s.Memory = core.NewFileMemory(nil)
}
// Normalize exposes core normalization logic
func Normalize(s string) string {
return core.Normalize(s)
}
// LevenshteinRatio exposes core Levenshtein distance logic
func LevenshteinRatio(s1, s2 string) int {
return core.LevenshteinRatio(s1, s2)
}