comments.go 891 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package stripper
  2. import (
  3. "bufio"
  4. "bytes"
  5. "io"
  6. "strings"
  7. "unicode"
  8. )
  9. type CommentStripper struct {
  10. Comment string
  11. Delimiter byte
  12. Whitespace bool
  13. r *bufio.Reader
  14. buf bytes.Buffer
  15. }
  16. func NewCommentStripper(r io.Reader) *CommentStripper {
  17. return &CommentStripper{
  18. Comment: "#",
  19. Delimiter: '\n',
  20. Whitespace: true,
  21. r: bufio.NewReader(r),
  22. }
  23. }
  24. func (r *CommentStripper) Read(p []byte) (int, error) {
  25. for {
  26. if r.buf.Len() >= len(p) {
  27. return r.buf.Read(p)
  28. }
  29. line, err := r.r.ReadString(r.Delimiter)
  30. if len(line) > 0 {
  31. checkLine := line
  32. if r.Whitespace {
  33. checkLine = strings.TrimLeftFunc(checkLine, unicode.IsSpace)
  34. }
  35. if strings.HasPrefix(checkLine, r.Comment) {
  36. // yay, skip this line
  37. continue
  38. }
  39. r.buf.WriteString(line)
  40. }
  41. if err != nil {
  42. if r.buf.Len() > 0 {
  43. return r.buf.Read(p)
  44. }
  45. return 0, err
  46. }
  47. }
  48. }