util.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // Format Table Header
  26. // Replace _ , . and spaces
  27. func Title(name string) string {
  28. name = strings.Replace(name, "_", " ", -1)
  29. name = strings.Replace(name, ".", " ", -1)
  30. name = strings.TrimSpace(name)
  31. return strings.ToUpper(name)
  32. }
  33. // Pad String
  34. // Attempts to play string in the center
  35. func Pad(s, pad string, width int) string {
  36. gap := width - DisplayWidth(s)
  37. if gap > 0 {
  38. gapLeft := int(math.Ceil(float64(gap / 2)))
  39. gapRight := gap - gapLeft
  40. return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight)
  41. }
  42. return s
  43. }
  44. // Pad String Right position
  45. // This would pace string at the left side fo the screen
  46. func PadRight(s, pad string, width int) string {
  47. gap := width - DisplayWidth(s)
  48. if gap > 0 {
  49. return s + strings.Repeat(string(pad), gap)
  50. }
  51. return s
  52. }
  53. // Pad String Left position
  54. // This would pace string at the right side fo the screen
  55. func PadLeft(s, pad string, width int) string {
  56. gap := width - DisplayWidth(s)
  57. if gap > 0 {
  58. return strings.Repeat(string(pad), gap) + s
  59. }
  60. return s
  61. }