forked from arduino/arduino-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsearch.go
81 lines (74 loc) · 2.35 KB
/
search.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
// This file is part of arduino-cli.
//
// Copyright 2020 ARDUINO SA (http://www.arduino.cc/)
//
// This software is released under the GNU General Public License version 3,
// which covers the main part of arduino-cli.
// The terms of this license can be found at:
// https://www.gnu.org/licenses/gpl-3.0.en.html
//
// You can be released from the requirements of the above licenses by purchasing
// a commercial license. Buying such a license is mandatory if you want to
// modify or otherwise use the software for commercial activities involving the
// Arduino software without disclosing the source code of your own applications.
// To purchase a commercial license, send an email to [email protected].
package utils
import (
"strings"
"unicode"
"golang.org/x/text/runes"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
)
// removeDiatrics removes accents and similar diatrics from unicode characters.
// An empty string is returned in case of errors.
// This might not be the best solution but it works well enough for our usecase,
// in the future we might want to use the golang.org/x/text/secure/precis package
// when its API will be finalized.
// From https://stackoverflow.com/a/26722698
func removeDiatrics(s string) (string, error) {
transformer := transform.Chain(
norm.NFD,
runes.Remove(runes.In(unicode.Mn)),
norm.NFC,
)
s, _, err := transform.String(transformer, s)
if err != nil {
return "", err
}
return s, nil
}
// Match returns true if all substrings are contained in str.
// Both str and substrings are transforms to lower case and have their
// accents and other unicode diatrics removed.
// If strings transformation fails an error is returned.
func Match(str string, substrings []string) bool {
clean := func(s string) string {
s = strings.ToLower(s)
if s2, err := removeDiatrics(s); err == nil {
return s2
}
return s
}
str = clean(str)
for _, sub := range substrings {
if !strings.Contains(str, clean(sub)) {
return false
}
}
return true
}
// MatchAny checks if query matches at least one of the
// string in arrayToMatch using the utils.Match function.
func MatchAny(query string, arrayToMatch []string) bool {
queryArgs := strings.Split(strings.TrimSpace(query), " ")
if len(queryArgs) == 0 {
return true
}
for _, t := range arrayToMatch {
if Match(t, queryArgs) {
return true
}
}
return false
}