etc.go 1.7 KB

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