git_reader.go 802 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package githttp
  2. import (
  3. "errors"
  4. "io"
  5. "regexp"
  6. )
  7. // GitReader scans for errors in the output of a git command
  8. type GitReader struct {
  9. // Underlying reader (to relay calls to)
  10. io.Reader
  11. // Error
  12. GitError error
  13. }
  14. // Regex to detect errors
  15. var (
  16. gitErrorRegex = regexp.MustCompile("error: (.*)")
  17. )
  18. // Implement the io.Reader interface
  19. func (g *GitReader) Read(p []byte) (n int, err error) {
  20. // Relay call
  21. n, err = g.Reader.Read(p)
  22. // Scan for errors
  23. g.scan(p)
  24. return n, err
  25. }
  26. func (g *GitReader) scan(data []byte) {
  27. // Already got an error
  28. // the main error will be the first error line
  29. if g.GitError != nil {
  30. return
  31. }
  32. matches := gitErrorRegex.FindSubmatch(data)
  33. // Skip, no matches found
  34. if matches == nil {
  35. return
  36. }
  37. g.GitError = errors.New(string(matches[1][:]))
  38. }