forked from peco/peco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matchers.go
463 lines (393 loc) · 10 KB
/
matchers.go
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package peco
import (
"fmt"
"os/exec"
"regexp"
"sort"
"strings"
"sync"
"unicode"
)
type MatcherSet struct {
current int
matchers []Matcher
mutex sync.Locker
}
func NewMatcherSet() *MatcherSet {
return &MatcherSet{0, []Matcher{}, newMutex()}
}
func (s *MatcherSet) GetCurrent() Matcher {
s.mutex.Lock()
i := s.current
s.mutex.Unlock()
return s.Get(i)
}
func (s *MatcherSet) Get(i int) Matcher {
s.mutex.Lock()
defer s.mutex.Unlock()
return s.matchers[i]
}
func (s *MatcherSet) SetCurrentByName(n string) bool {
s.mutex.Lock()
defer s.mutex.Unlock()
for i, m := range s.matchers {
if m.String() == n {
s.current = i
return true
}
}
return false
}
func (s *MatcherSet) Add(m Matcher) error {
s.mutex.Lock()
defer s.mutex.Unlock()
if err := m.Verify(); err != nil {
return fmt.Errorf("verification for custom matcher failed: %s", err)
}
s.matchers = append(s.matchers, m)
return nil
}
// Rotate rotates the matchers
func (s *MatcherSet) Rotate() {
s.mutex.Lock()
defer s.mutex.Unlock()
s.current++
if s.current >= len(s.matchers) {
s.current = 0
}
}
// Matcher interface defines the API for things that want to
// match against the buffer
type Matcher interface {
// Match takes in three parameters.
//
// The first chan is the channel where cancel requests are sent.
// If you receive a request here, you should stop running your query.
//
// The second is the query. Do what you want with it
//
// The third is the buffer in which to match the query against.
Line(chan struct{}, string, []Line) []Line
String() string
// This is fugly. We just added a method only for CustomMatcner.
// Must think about this again
Verify() error
}
// These are used as keys in the config file
const (
IgnoreCaseMatch = "IgnoreCase"
CaseSensitiveMatch = "CaseSensitive"
SmartCaseMatch = "SmartCase"
RegexpMatch = "Regexp"
)
var ignoreCaseFlags = []string{"i"}
var defaultFlags = []string{}
type regexpFlags interface {
flags(string) []string
}
type regexpFlagList []string
func (r regexpFlagList) flags(_ string) []string {
return []string(r)
}
type regexpFlagFunc func(string) []string
func (r regexpFlagFunc) flags(s string) []string {
return r(s)
}
// RegexpMatcher is the most basic matcher
type RegexpMatcher struct {
enableSep bool
flags regexpFlags
quotemeta bool
}
// CaseSensitiveMatcher extends the RegxpMatcher, but always
// turns off the ignore-case flag in the regexp
type CaseSensitiveMatcher struct {
*RegexpMatcher
}
// IgnoreCaseMatcher extends the RegexpMatcher, and always
// turns ON the ignore-case flag in the regexp
type IgnoreCaseMatcher struct {
*RegexpMatcher
}
// SmartCaseMatcher turns ON the ignore-case flag in the regexp
// if the query contains a upper-case character
type SmartCaseMatcher struct {
*RegexpMatcher
}
// CustomMatcher spawns a new process to filter the buffer
// in peco, and uses the output in its Stdout to figure
// out what to display
type CustomMatcher struct {
enableSep bool
name string
args []string
}
// NewCaseSensitiveMatcher creates a new CaseSensitiveMatcher
func NewCaseSensitiveMatcher(enableSep bool) *CaseSensitiveMatcher {
m := &CaseSensitiveMatcher{NewRegexpMatcher(enableSep)}
m.quotemeta = true
return m
}
// NewIgnoreCaseMatcher creates a new IgnoreCaseMatcher
func NewIgnoreCaseMatcher(enableSep bool) *IgnoreCaseMatcher {
m := &IgnoreCaseMatcher{NewRegexpMatcher(enableSep)}
m.flags = regexpFlagList(ignoreCaseFlags)
m.quotemeta = true
return m
}
// NewRegexpMatcher creates a new RegexpMatcher
func NewRegexpMatcher(enableSep bool) *RegexpMatcher {
return &RegexpMatcher{
enableSep,
regexpFlagList(defaultFlags),
false,
}
}
// Verify always returns nil
func (m *RegexpMatcher) Verify() error {
return nil
}
func containsUpper(query string) bool {
for _, c := range query {
if unicode.IsUpper(c) {
return true
}
}
return false
}
// NewSmartCaseMatcher creates a new SmartCaseMatcher
func NewSmartCaseMatcher(enableSep bool) *SmartCaseMatcher {
m := &SmartCaseMatcher{NewRegexpMatcher(enableSep)}
m.flags = regexpFlagFunc(func(q string) []string {
if containsUpper(q) {
return defaultFlags
}
return []string{"i"}
})
m.quotemeta = true
return m
}
// NewCustomMatcher creates a new CustomMatcher
func NewCustomMatcher(enableSep bool, name string, args []string) *CustomMatcher {
return &CustomMatcher{enableSep, name, args}
}
// Verify checks to see that the executable given to CustomMatcher
// is actual found and is executable via exec.LookPath
func (m *CustomMatcher) Verify() error {
if len(m.args) == 0 {
return fmt.Errorf("no executable specified for custom matcher '%s'", m.name)
}
if _, err := exec.LookPath(m.args[0]); err != nil {
return err
}
return nil
}
func regexpFor(q string, flags []string, quotemeta bool) (*regexp.Regexp, error) {
reTxt := q
if quotemeta {
reTxt = regexp.QuoteMeta(q)
}
if flags != nil && len(flags) > 0 {
reTxt = fmt.Sprintf("(?%s)%s", strings.Join(flags, ""), reTxt)
}
re, err := regexp.Compile(reTxt)
if err != nil {
return nil, err
}
return re, nil
}
func (m *RegexpMatcher) queryToRegexps(query string) ([]*regexp.Regexp, error) {
queries := strings.Split(strings.TrimSpace(query), " ")
regexps := make([]*regexp.Regexp, 0)
for _, q := range queries {
re, err := regexpFor(q, m.flags.flags(query), m.quotemeta)
if err != nil {
return nil, err
}
regexps = append(regexps, re)
}
return regexps, nil
}
func (m *RegexpMatcher) String() string {
return RegexpMatch
}
func (m *CaseSensitiveMatcher) String() string {
return CaseSensitiveMatch
}
func (m *IgnoreCaseMatcher) String() string {
return IgnoreCaseMatch
}
func (m *SmartCaseMatcher) String() string {
return SmartCaseMatch
}
func (m *CustomMatcher) String() string {
return m.name
}
// sort related stuff
type byStart [][]int
func (m byStart) Len() int {
return len(m)
}
func (m byStart) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m byStart) Less(i, j int) bool {
return m[i][0] < m[j][0]
}
// Match does the heavy lifting, and matches `q` against `buffer`.
// While it is doing the match, it also listens for messages
// via `quit`. If anything is received via `quit`, the match
// is halted.
func (m *RegexpMatcher) Line(quit chan struct{}, q string, buffer []Line) []Line {
results := []Line{}
regexps, err := m.queryToRegexps(q)
if err != nil {
return results
}
// The actual matching is done in a separate goroutine
iter := make(chan Line, len(buffer))
go func() {
// This protects us from panics, caused when we cancel the
// query and forcefully close the channel (and thereby
// causing a "close of a closed channel"
defer func() { recover() }()
// This must be here to make sure the channel is properly
// closed in normal cases
defer close(iter)
// Iterate through the lines, and do the match.
// Upon success, send it through the channel
for _, match := range buffer {
ms := m.MatchAllRegexps(regexps, match.DisplayString())
if ms == nil {
continue
}
iter <- NewMatchedLine(match.Buffer(), m.enableSep, ms)
}
iter <- nil
}()
MATCH:
for {
select {
case <-quit:
// If we recieved a cancel request, we immediately bail out.
// It's a little dirty, but we focefully terminate the other
// goroutine by closing the channel, and invoking a panic in the
// goroutine above
// There's a possibility that the match fails early and the
// cancel happens after iter has been closed. It's totally okay
// for us to try to close iter, but trying to detect if the
// channel can be closed safely synchronously is really hard
// so we punt it by letting the close() happen at a separate
// goroutine, protected by a defer recover()
go func() {
defer func() { recover() }()
close(iter)
}()
break MATCH
case match := <-iter:
// Receive elements from the goroutine performing the match
if match == nil {
break MATCH
}
results = append(results, match)
}
}
return results
}
// MatchAllRegexps matches all the regexps in `regexps` against line
func (m *RegexpMatcher) MatchAllRegexps(regexps []*regexp.Regexp, line string) [][]int {
matches := make([][]int, 0)
allMatched := true
Line:
for _, re := range regexps {
match := re.FindAllStringSubmatchIndex(line, -1)
if match == nil {
allMatched = false
break Line
}
for _, ma := range match {
start, end := ma[0], ma[1]
for _, m := range matches {
if start >= m[0] && start < m[1] {
continue Line
}
if start < m[0] && end >= m[0] {
continue Line
}
}
matches = append(matches, ma)
}
}
if !allMatched {
return nil
}
sort.Sort(byStart(matches))
return matches
}
// Match matches `q` aginst `buffer`
func (m *CustomMatcher) Line(quit chan struct{}, q string, buffer []Line) []Line {
if len(m.args) < 1 {
return []Line{}
}
results := []Line{}
if q == "" {
for _, match := range buffer {
results = append(results, NewMatchedLine(match.Buffer(), m.enableSep, nil))
}
return results
}
// Receive elements from the goroutine performing the match
lines := []Line{}
matcherInput := ""
for _, match := range buffer {
matcherInput += match.DisplayString() + "\n"
lines = append(lines, match)
}
args := []string{}
for _, arg := range m.args {
if arg == "$QUERY" {
arg = q
}
args = append(args, arg)
}
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = strings.NewReader(matcherInput)
// See RegexpMatcher.Match() for explanation of constructs
iter := make(chan Line, len(buffer))
go func() {
defer func() { recover() }()
defer func() {
if p := cmd.Process; p != nil {
p.Kill()
}
close(iter)
}()
b, err := cmd.Output()
if err != nil {
iter <- nil
}
for _, line := range strings.Split(string(b), "\n") {
if len(line) > 0 {
iter <- NewMatchedLine(line, m.enableSep, nil)
}
}
iter <- nil
}()
MATCH:
for {
select {
case <-quit:
go func() {
defer func() { recover() }()
close(iter)
}()
break MATCH
case match := <-iter:
if match == nil {
break MATCH
}
results = append(results, match)
}
}
return results
}