| 1 |
// Copyright (c) 2021, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package trace |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"io" |
| 12 |
"strings" |
| 13 |
) |
| 14 |
|
| 15 |
// Level is a level when retrieving a stack trace. |
| 16 |
type Level struct { |
| 17 |
Package string |
| 18 |
Func string |
| 19 |
FileLine string |
| 20 |
} |
| 21 |
|
| 22 |
// Stack is a simple stack trace. |
| 23 |
type Stack []Level |
| 24 |
|
| 25 |
// Match returns true if the ith level of s matches pkg (if not empty) |
| 26 |
// and any function in anyFunc. |
| 27 |
// |
| 28 |
// If anyFunc is empty, only the package is tested. |
| 29 |
// |
| 30 |
// If a function in anyFunc ends with "*", only the prefix is checked. |
| 31 |
func (s Stack) Match(i int, pkg string, anyFunc ...string) bool { |
| 32 |
if i < 0 { |
| 33 |
i = len(s) + i |
| 34 |
} |
| 35 |
if i < 0 || i >= len(s) { |
| 36 |
return false |
| 37 |
} |
| 38 |
|
| 39 |
level := s[i] |
| 40 |
|
| 41 |
if pkg != "" && level.Package != pkg { |
| 42 |
return false |
| 43 |
} |
| 44 |
|
| 45 |
if len(anyFunc) == 0 { |
| 46 |
return true |
| 47 |
} |
| 48 |
|
| 49 |
for _, fn := range anyFunc { |
| 50 |
if strings.HasSuffix(fn, "*") { |
| 51 |
if strings.HasPrefix(level.Func, fn[:len(fn)-1]) { |
| 52 |
return true |
| 53 |
} |
| 54 |
} else if level.Func == fn { |
| 55 |
return true |
| 56 |
} |
| 57 |
} |
| 58 |
return false |
| 59 |
} |
| 60 |
|
| 61 |
// IsRelevant returns true if the stack contains more than one level, |
| 62 |
// or if the single level has a path with at least one directory. |
| 63 |
func (s Stack) IsRelevant() bool { |
| 64 |
return len(s) > 1 || (len(s) > 0 && strings.ContainsAny(s[0].FileLine, `/\`)) |
| 65 |
} |
| 66 |
|
| 67 |
// Dump writes the stack to w. |
| 68 |
func (s Stack) Dump(w io.Writer) { |
| 69 |
fnMaxLen := 0 |
| 70 |
for _, level := range s { |
| 71 |
if len(level.Func) > fnMaxLen { |
| 72 |
fnMaxLen = len(level.Func) |
| 73 |
} |
| 74 |
} |
| 75 |
fnMaxLen += 2 |
| 76 |
|
| 77 |
nl := "" |
| 78 |
for _, level := range s { |
| 79 |
fmt.Fprintf(w, "%s\t%-*s %s", nl, fnMaxLen, level.Func+"()", level.FileLine) //nolint: errcheck |
| 80 |
nl = "\n" |
| 81 |
} |
| 82 |
} |