interpol.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. // Package interpol provides utility functions for doing format-string like
  2. // string interpolation using named parameters.
  3. // Currently, a template only accepts variable placeholders delimited by brace
  4. // characters (eg. "Hello {foo} {bar}").
  5. package interpol
  6. import (
  7. "bytes"
  8. "errors"
  9. "io"
  10. "strings"
  11. )
  12. // Errors returned when formatting templates.
  13. var (
  14. ErrUnexpectedClose = errors.New("interpol: unexpected close in template")
  15. ErrExpectingClose = errors.New("interpol: expecting close in template")
  16. ErrKeyNotFound = errors.New("interpol: key not found")
  17. ErrReadByteFailed = errors.New("interpol: read byte failed")
  18. )
  19. // Func receives the placeholder key and writes to the io.Writer. If an error
  20. // happens, the function can return an error, in which case the interpolation
  21. // will be aborted.
  22. type Func func(key string, w io.Writer) error
  23. // New creates a new interpolator with the given list of options.
  24. // You can use options such as the ones returned by WithTemplate, WithFormat
  25. // and WithOutput.
  26. func New(opts ...Option) *Interpolator {
  27. opts2 := &Options{}
  28. setOptions(opts, newOptionSetter(opts2))
  29. return NewWithOptions(opts2)
  30. }
  31. // NewWithOptions creates a new interpolator with the given options.
  32. func NewWithOptions(opts *Options) *Interpolator {
  33. return &Interpolator{
  34. template: templateReader(opts),
  35. output: outputWriter(opts),
  36. format: opts.Format,
  37. rb: make([]rune, 0, 64),
  38. start: -1,
  39. closing: false,
  40. }
  41. }
  42. // Interpolator interpolates Template to Output, according to Format.
  43. type Interpolator struct {
  44. template io.RuneReader
  45. output runeWriter
  46. format Func
  47. rb []rune
  48. start int
  49. closing bool
  50. }
  51. // Interpolate reads runes from Template and writes them to Output, with the
  52. // exception of placeholders which are passed to Format.
  53. func (i *Interpolator) Interpolate() error {
  54. for pos := 0; ; pos++ {
  55. r, _, err := i.template.ReadRune()
  56. if err != nil {
  57. if err == io.EOF {
  58. break
  59. }
  60. return err
  61. }
  62. if err := i.parse(r, pos); err != nil {
  63. return err
  64. }
  65. }
  66. return i.finish()
  67. }
  68. func (i *Interpolator) parse(r rune, pos int) error {
  69. switch r {
  70. case '{':
  71. return i.open(pos)
  72. case '}':
  73. return i.close()
  74. default:
  75. return i.append(r)
  76. }
  77. }
  78. func (i *Interpolator) open(pos int) error {
  79. if i.closing {
  80. return ErrUnexpectedClose
  81. }
  82. if i.start >= 0 {
  83. if _, err := i.output.WriteRune('{'); err != nil {
  84. return err
  85. }
  86. i.start = -1
  87. } else {
  88. i.start = pos + 1
  89. }
  90. return nil
  91. }
  92. func (i *Interpolator) close() error {
  93. if i.start >= 0 {
  94. if err := i.format(string(i.rb), i.output); err != nil {
  95. return err
  96. }
  97. i.rb = i.rb[:0]
  98. i.start = -1
  99. } else if i.closing {
  100. i.closing = false
  101. if _, err := i.output.WriteRune('}'); err != nil {
  102. return err
  103. }
  104. } else {
  105. i.closing = true
  106. }
  107. return nil
  108. }
  109. func (i *Interpolator) append(r rune) error {
  110. if i.closing {
  111. return ErrUnexpectedClose
  112. }
  113. if i.start < 0 {
  114. _, err := i.output.WriteRune(r)
  115. return err
  116. }
  117. i.rb = append(i.rb, r)
  118. return nil
  119. }
  120. func (i *Interpolator) finish() error {
  121. if i.start >= 0 {
  122. return ErrExpectingClose
  123. }
  124. if i.closing {
  125. return ErrUnexpectedClose
  126. }
  127. return nil
  128. }
  129. // WithFunc interpolates the specified template with replacements using the
  130. // given function.
  131. func WithFunc(template string, format Func) (string, error) {
  132. buffer := bytes.NewBuffer(make([]byte, 0, len(template)))
  133. opts := &Options{
  134. Template: strings.NewReader(template),
  135. Output: buffer,
  136. Format: format,
  137. }
  138. i := NewWithOptions(opts)
  139. if err := i.Interpolate(); err != nil {
  140. return "", err
  141. }
  142. return buffer.String(), nil
  143. }
  144. // WithMap interpolates the specified template with replacements using the
  145. // given map. If a placeholder is used for which a value is not found, an error
  146. // is returned.
  147. func WithMap(template string, m map[string]string) (string, error) {
  148. format := func(key string, w io.Writer) error {
  149. value, ok := m[key]
  150. if !ok {
  151. return ErrKeyNotFound
  152. }
  153. _, err := w.Write([]byte(value))
  154. return err
  155. }
  156. return WithFunc(template, format)
  157. }