fix: warn on ambiguous contains match, use sort.Slice in sortedCalls

This commit is contained in:
thibaud-leclere 2026-05-12 10:08:19 +02:00
parent f3b14fd068
commit 302d2d9b90
2 changed files with 17 additions and 20 deletions

View file

@ -61,6 +61,9 @@ func Callees(p *cachegrind.Profile, name string, topN int) string {
}
var sb strings.Builder
if len(fns) > 1 {
fmt.Fprintf(&sb, "Warning: %d functions match %q — showing all\n\n", len(fns), name)
}
for _, fn := range fns {
fmt.Fprintf(&sb, "Callees of %q [%s]\n", fn.Name, fn.File)
if len(fn.Calls) == 0 {

View file

@ -3,6 +3,7 @@ package tools
import (
"context"
"fmt"
"sort"
"strings"
"github.com/mark3labs/mcp-go/mcp"
@ -61,6 +62,9 @@ func Callers(p *cachegrind.Profile, name string, topN int) string {
}
var sb strings.Builder
if len(fns) > 1 {
fmt.Fprintf(&sb, "Warning: %d functions match %q — showing all\n\n", len(fns), name)
}
for _, fn := range fns {
fmt.Fprintf(&sb, "Callers of %q [%s]\n", fn.Name, fn.File)
if len(fn.CalledBy) == 0 {
@ -87,25 +91,15 @@ func Callers(p *cachegrind.Profile, name string, topN int) string {
func sortedCalls(calls []*cachegrind.Call) []*cachegrind.Call {
out := make([]*cachegrind.Call, len(calls))
copy(out, calls)
sortCallSlice(out)
sort.Slice(out, func(i, j int) bool {
ci, cj := int64(0), int64(0)
if len(out[i].Costs) > 0 {
ci = out[i].Costs[0]
}
if len(out[j].Costs) > 0 {
cj = out[j].Costs[0]
}
return ci > cj
})
return out
}
func sortCallSlice(calls []*cachegrind.Call) {
for i := 1; i < len(calls); i++ {
for j := i; j > 0; j-- {
ci, cj := int64(0), int64(0)
if len(calls[j].Costs) > 0 {
ci = calls[j].Costs[0]
}
if len(calls[j-1].Costs) > 0 {
cj = calls[j-1].Costs[0]
}
if ci > cj {
calls[j], calls[j-1] = calls[j-1], calls[j]
} else {
break
}
}
}
}