columnize.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package columnize
  2. import (
  3. "bytes"
  4. "fmt"
  5. "strings"
  6. )
  7. // Config can be used to tune certain parameters which affect the way
  8. // in which Columnize will format output text.
  9. type Config struct {
  10. // The string by which the lines of input will be split.
  11. Delim string
  12. // The string by which columns of output will be separated.
  13. Glue string
  14. // The string by which columns of output will be prefixed.
  15. Prefix string
  16. // A replacement string to replace empty fields.
  17. Empty string
  18. // NoTrim disables automatic trimming of inputs.
  19. NoTrim bool
  20. }
  21. // DefaultConfig returns a *Config with default values.
  22. func DefaultConfig() *Config {
  23. return &Config{
  24. Delim: "|",
  25. Glue: " ",
  26. Prefix: "",
  27. Empty: "",
  28. NoTrim: false,
  29. }
  30. }
  31. // MergeConfig merges two config objects together and returns the resulting
  32. // configuration. Values from the right take precedence over the left side.
  33. func MergeConfig(a, b *Config) *Config {
  34. // Return quickly if either side was nil
  35. if a == nil {
  36. return b
  37. }
  38. if b == nil {
  39. return a
  40. }
  41. var result Config = *a
  42. if b.Delim != "" {
  43. result.Delim = b.Delim
  44. }
  45. if b.Glue != "" {
  46. result.Glue = b.Glue
  47. }
  48. if b.Prefix != "" {
  49. result.Prefix = b.Prefix
  50. }
  51. if b.Empty != "" {
  52. result.Empty = b.Empty
  53. }
  54. if b.NoTrim {
  55. result.NoTrim = true
  56. }
  57. return &result
  58. }
  59. // stringFormat, given a set of column widths and the number of columns in
  60. // the current line, returns a sprintf-style format string which can be used
  61. // to print output aligned properly with other lines using the same widths set.
  62. func stringFormat(c *Config, widths []int, columns int) string {
  63. // Create the buffer with an estimate of the length
  64. buf := bytes.NewBuffer(make([]byte, 0, (6+len(c.Glue))*columns))
  65. // Start with the prefix, if any was given. The buffer will not return an
  66. // error so it does not need to be handled
  67. buf.WriteString(c.Prefix)
  68. // Create the format string from the discovered widths
  69. for i := 0; i < columns && i < len(widths); i++ {
  70. if i == columns-1 {
  71. buf.WriteString("%s\n")
  72. } else {
  73. fmt.Fprintf(buf, "%%-%ds%s", widths[i], c.Glue)
  74. }
  75. }
  76. return buf.String()
  77. }
  78. // elementsFromLine returns a list of elements, each representing a single
  79. // item which will belong to a column of output.
  80. func elementsFromLine(config *Config, line string) []interface{} {
  81. separated := strings.Split(line, config.Delim)
  82. elements := make([]interface{}, len(separated))
  83. for i, field := range separated {
  84. value := field
  85. if !config.NoTrim {
  86. value = strings.TrimSpace(field)
  87. }
  88. // Apply the empty value, if configured.
  89. if value == "" && config.Empty != "" {
  90. value = config.Empty
  91. }
  92. elements[i] = value
  93. }
  94. return elements
  95. }
  96. // runeLen calculates the number of visible "characters" in a string
  97. func runeLen(s string) int {
  98. l := 0
  99. for _ = range s {
  100. l++
  101. }
  102. return l
  103. }
  104. // widthsFromLines examines a list of strings and determines how wide each
  105. // column should be considering all of the elements that need to be printed
  106. // within it.
  107. func widthsFromLines(config *Config, lines []string) []int {
  108. widths := make([]int, 0, 8)
  109. for _, line := range lines {
  110. elems := elementsFromLine(config, line)
  111. for i := 0; i < len(elems); i++ {
  112. l := runeLen(elems[i].(string))
  113. if len(widths) <= i {
  114. widths = append(widths, l)
  115. } else if widths[i] < l {
  116. widths[i] = l
  117. }
  118. }
  119. }
  120. return widths
  121. }
  122. // Format is the public-facing interface that takes a list of strings and
  123. // returns nicely aligned column-formatted text.
  124. func Format(lines []string, config *Config) string {
  125. conf := MergeConfig(DefaultConfig(), config)
  126. widths := widthsFromLines(conf, lines)
  127. // Estimate the buffer size
  128. glueSize := len(conf.Glue)
  129. var size int
  130. for _, w := range widths {
  131. size += w + glueSize
  132. }
  133. size *= len(lines)
  134. // Create the buffer
  135. buf := bytes.NewBuffer(make([]byte, 0, size))
  136. // Create a cache for the string formats
  137. fmtCache := make(map[int]string, 16)
  138. // Create the formatted output using the format string
  139. for _, line := range lines {
  140. elems := elementsFromLine(conf, line)
  141. // Get the string format using cache
  142. numElems := len(elems)
  143. stringfmt, ok := fmtCache[numElems]
  144. if !ok {
  145. stringfmt = stringFormat(conf, widths, numElems)
  146. fmtCache[numElems] = stringfmt
  147. }
  148. fmt.Fprintf(buf, stringfmt, elems...)
  149. }
  150. // Get the string result
  151. result := buf.String()
  152. // Remove trailing newline without removing leading/trailing space
  153. if n := len(result); n > 0 && result[n-1] == '\n' {
  154. result = result[:n-1]
  155. }
  156. return result
  157. }
  158. // SimpleFormat is a convenience function to format text with the defaults.
  159. func SimpleFormat(lines []string) string {
  160. return Format(lines, nil)
  161. }