outputOnce executes a function only once per unique message and function type. It uses a SHA256 hash of the formatted message to detect duplicates.
(format string, a []any, fn func(string, ...any))
| 33 | // outputOnce executes a function only once per unique message and function type. |
| 34 | // It uses a SHA256 hash of the formatted message to detect duplicates. |
| 35 | func outputOnce(format string, a []any, fn func(string, ...any)) { |
| 36 | // Format the message first to create the cache key |
| 37 | var message string |
| 38 | if a != nil { |
| 39 | message = fmt.Sprintf(format, a...) |
| 40 | } else { |
| 41 | message = format |
| 42 | } |
| 43 | |
| 44 | // Create hash of the message and function pointer to create unique cache key |
| 45 | msgKey := HashSalt(message) |
| 46 | fnKey := fmt.Sprintf("%p", fn) // Use function pointer as key |
| 47 | |
| 48 | outputOnceMutex.Lock() |
| 49 | // Initialize the function type cache if it doesn't exist |
| 50 | if outputOnceCache[fnKey] == nil { |
| 51 | outputOnceCache[fnKey] = map[string]bool{} |
| 52 | } |
| 53 | |
| 54 | // Check if we've already executed this message for this function type |
| 55 | if outputOnceCache[fnKey][msgKey] { |
| 56 | outputOnceMutex.Unlock() |
| 57 | return |
| 58 | } |
| 59 | // Mark as shown |
| 60 | outputOnceCache[fnKey][msgKey] = true |
| 61 | outputOnceMutex.Unlock() |
| 62 | |
| 63 | // execute the function |
| 64 | fn(format, a...) |
| 65 | } |
| 66 | |
| 67 | // Failed will print a red error message and exit with failure. |
| 68 | func Failed(format string, a ...any) { |
no test coverage detected