etc.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2023 The Knuth Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package knuth // modernc.org/knuth
  5. import (
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. )
  12. // origin returns caller's short position, skipping skip frames.
  13. func origin(skip int) string {
  14. pc, fn, fl, _ := runtime.Caller(skip)
  15. f := runtime.FuncForPC(pc)
  16. var fns string
  17. if f != nil {
  18. fns = f.Name()
  19. if x := strings.LastIndex(fns, "."); x > 0 {
  20. fns = fns[x+1:]
  21. }
  22. if strings.HasPrefix(fns, "func") {
  23. num := true
  24. for _, c := range fns[len("func"):] {
  25. if c < '0' || c > '9' {
  26. num = false
  27. break
  28. }
  29. }
  30. if num {
  31. return origin(skip + 2)
  32. }
  33. }
  34. }
  35. return fmt.Sprintf("%s:%d:%s", filepath.Base(fn), fl, fns)
  36. }
  37. // todo prints and returns caller's position and an optional message tagged with TODO. Output goes to stderr.
  38. //
  39. //lint:ignore U1000 whatever
  40. func todo(s string, args ...interface{}) string {
  41. switch {
  42. case s == "":
  43. s = fmt.Sprintf(strings.Repeat("%v ", len(args)), args...)
  44. default:
  45. s = fmt.Sprintf(s, args...)
  46. }
  47. r := fmt.Sprintf("%s\n\tTODO %s", origin(2), s)
  48. // fmt.Fprintf(os.Stderr, "%s\n", r)
  49. // os.Stdout.Sync()
  50. return r
  51. }
  52. // trc prints and returns caller's position and an optional message tagged with TRC. Output goes to stderr.
  53. //
  54. //lint:ignore U1000 whatever
  55. func trc(s string, args ...interface{}) string {
  56. switch {
  57. case s == "":
  58. s = fmt.Sprintf(strings.Repeat("%v ", len(args)), args...)
  59. default:
  60. s = fmt.Sprintf(s, args...)
  61. }
  62. r := fmt.Sprintf("%s: TRC %s", origin(2), s)
  63. fmt.Fprintf(os.Stderr, "%s\n", r)
  64. os.Stderr.Sync()
  65. return r
  66. }