util.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2014 Oleku Konko All rights reserved.
  2. // Use of this source code is governed by a MIT
  3. // license that can be found in the LICENSE file.
  4. // This module is a Table Writer API for the Go Programming Language.
  5. // The protocols were written in pure Go and works on windows and unix systems
  6. package tablewriter
  7. import (
  8. "math"
  9. "regexp"
  10. "strings"
  11. "github.com/mattn/go-runewidth"
  12. )
  13. var ansi = regexp.MustCompile("\033\\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]")
  14. func DisplayWidth(str string) int {
  15. return runewidth.StringWidth(ansi.ReplaceAllLiteralString(str, ""))
  16. }
  17. // Simple Condition for string
  18. // Returns value based on condition
  19. func ConditionString(cond bool, valid, inValid string) string {
  20. if cond {
  21. return valid
  22. }
  23. return inValid
  24. }
  25. func isNumOrSpace(r rune) bool {
  26. return ('0' <= r && r <= '9') || r == ' '
  27. }
  28. // Format Table Header
  29. // Replace _ , . and spaces
  30. func Title(name string) string {
  31. origLen := len(name)
  32. rs := []rune(name)
  33. for i, r := range rs {
  34. switch r {
  35. case '_':
  36. rs[i] = ' '
  37. case '.':
  38. // ignore floating number 0.0
  39. if (i != 0 && !isNumOrSpace(rs[i-1])) || (i != len(rs)-1 && !isNumOrSpace(rs[i+1])) {
  40. rs[i] = ' '
  41. }
  42. }
  43. }
  44. name = string(rs)
  45. name = strings.TrimSpace(name)
  46. if len(name) == 0 && origLen > 0 {
  47. // Keep at least one character. This is important to preserve
  48. // empty lines in multi-line headers/footers.
  49. name = " "
  50. }
  51. return strings.ToUpper(name)
  52. }
  53. // Pad String
  54. // Attempts to place string in the center
  55. func Pad(s, pad string, width int) string {
  56. gap := width - DisplayWidth(s)
  57. if gap > 0 {
  58. gapLeft := int(math.Ceil(float64(gap / 2)))
  59. gapRight := gap - gapLeft
  60. return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight)
  61. }
  62. return s
  63. }
  64. // Pad String Right position
  65. // This would place string at the left side of the screen
  66. func PadRight(s, pad string, width int) string {
  67. gap := width - DisplayWidth(s)
  68. if gap > 0 {
  69. return s + strings.Repeat(string(pad), gap)
  70. }
  71. return s
  72. }
  73. // Pad String Left position
  74. // This would place string at the right side of the screen
  75. func PadLeft(s, pad string, width int) string {
  76. gap := width - DisplayWidth(s)
  77. if gap > 0 {
  78. return strings.Repeat(string(pad), gap) + s
  79. }
  80. return s
  81. }