Skip to content

Commit fc5029d

Browse files
committed
Fixed nil exception on some rare case with multiple libs selection
The closestmatch algorithm may return 'nil' if none of the candidate libraries has enough matching of the name. In this case just return the first library in alphanumeric ordering. See arduino/Arduino#9242
1 parent ba1370b commit fc5029d

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-4
lines changed

arduino/libraries/librarieslist.go

+8
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,14 @@ func (list *List) SortByArchitecturePriority(arch string) {
6161
})
6262
}
6363

64+
// SortByName sorts the libraries by name
65+
func (list *List) SortByName() {
66+
sort.Slice(*list, func(i, j int) bool {
67+
a, b := (*list)[i], (*list)[j]
68+
return a.Name < b.Name
69+
})
70+
}
71+
6472
/*
6573
// HasHigherPriority returns true if library x has higher priority compared to library
6674
// y for the given header and architecture.

arduino/libraries/librariesresolver/cpp.go

+7-4
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,14 @@ func (resolver *Cpp) ResolveFor(header, architecture string) *libraries.Library
105105

106106
// If more than one library qualifies use the "closestmatch" algorithm to
107107
// find the best matching one (instead of choosing it randomly)
108-
winner := findLibraryWithNameBestDistance(header, found)
109-
if winner != nil {
110-
logrus.WithField("lib", winner.Name).Info(" library with the best mathing name")
108+
if best := findLibraryWithNameBestDistance(header, found); best != nil {
109+
logrus.WithField("lib", best.Name).Info(" library with the best mathing name")
110+
return best
111111
}
112-
return winner
112+
113+
found.SortByName()
114+
logrus.WithField("lib", found[0].Name).Info(" first library in alphabetic order")
115+
return found[0]
113116
}
114117

115118
func simplify(name string) string {

arduino/libraries/librariesresolver/cpp_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ var l5 = &libraries.Library{Name: "Yet Another Calculus Lib Improved", Location:
3232
var l6 = &libraries.Library{Name: "Calculus Unified Lib", Location: libraries.Sketchbook}
3333
var l7 = &libraries.Library{Name: "AnotherLib", Location: libraries.Sketchbook}
3434

35+
func TestClosestMatchWithTotallyDifferentNames(t *testing.T) {
36+
libraryList := libraries.List{}
37+
libraryList.Add(l5)
38+
libraryList.Add(l6)
39+
libraryList.Add(l7)
40+
resolver := NewCppResolver()
41+
resolver.headers["XYZ.h"] = libraryList
42+
res := resolver.ResolveFor("XYZ.h", "xyz")
43+
require.NotNil(t, res)
44+
require.Equal(t, l7, res, "selected library")
45+
}
46+
3547
func TestCppHeaderPriority(t *testing.T) {
3648
r1 := computePriority(l1, "calculus_lib.h", "avr")
3749
r2 := computePriority(l2, "calculus_lib.h", "avr")

0 commit comments

Comments
 (0)