fileterm.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Public Domain Software
  3. *
  4. * I (Matthias Ladkau) am the author of the source code in this file.
  5. * I have placed the source code in this file in the public domain.
  6. *
  7. * For further information see: http://creativecommons.org/publicdomain/zero/1.0/
  8. */
  9. package termutil
  10. import (
  11. "bufio"
  12. "io"
  13. )
  14. /*
  15. filereadingTerminalMixin first provides lines from a given file before delegating
  16. to a wrapped terminal
  17. */
  18. type filereadingTerminalMixin struct {
  19. ConsoleLineTerminal // Terminal which is being wrapped
  20. lines []string // File containing the first lines
  21. linePointer int // Pointer to the next line
  22. termOnEOF bool // Flag if the terminal should send EOT after last file line
  23. }
  24. /*
  25. AddFileReadingWrapper wraps a given terminal and provides the fist lines of
  26. a given input reader as first lines before delegating to the wrapped terminal.
  27. Terminates after the file has been red if termOnEOF is set.
  28. */
  29. func AddFileReadingWrapper(term ConsoleLineTerminal, r io.Reader, termOnEOF bool) (ConsoleLineTerminal, error) {
  30. var ret ConsoleLineTerminal
  31. fileterm := &filereadingTerminalMixin{term, nil, 0, termOnEOF}
  32. scanner := bufio.NewScanner(r)
  33. for scanner.Scan() {
  34. fileterm.lines = append(fileterm.lines, scanner.Text())
  35. }
  36. ret = fileterm
  37. return ret, nil
  38. }
  39. /*
  40. NextLine returns the next line in the lines array. After the final line it
  41. either delegates to the wrapped terminal or sends EOT.
  42. */
  43. func (ht *filereadingTerminalMixin) NextLine() (string, error) {
  44. var line string
  45. var err error
  46. if ht.linePointer < len(ht.lines) {
  47. line = ht.lines[ht.linePointer]
  48. ht.linePointer++
  49. } else if !ht.termOnEOF {
  50. line, err = ht.ConsoleLineTerminal.NextLine()
  51. } else {
  52. line = "\x04"
  53. }
  54. return line, err
  55. }