|
| 1 | +package gitdiff |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "io" |
| 6 | +) |
| 7 | + |
| 8 | +// StringReader is the interface that wraps the ReadString method. |
| 9 | +type StringReader interface { |
| 10 | + // ReadString reads until the first occurrence of delim in the input, |
| 11 | + // returning a string containing the data up to and including the |
| 12 | + // delimiter. If ReadString encounters an error before finding a delimiter, |
| 13 | + // it returns the data read before the error and the error itself (often |
| 14 | + // io.EOF). ReadString returns err != nil if and only if the returned data |
| 15 | + // does not end in delim. |
| 16 | + ReadString(delim byte) (string, error) |
| 17 | +} |
| 18 | + |
| 19 | +// LineReader is the interface that wraps the ReadLine method. |
| 20 | +type LineReader interface { |
| 21 | + // ReadLine reads the next full line in the input, returing the the data |
| 22 | + // including the line ending character(s) and the zero-indexed line number. |
| 23 | + // If ReadLine encounters an error before reaching the end of the line, it |
| 24 | + // returns the data read before the error and the error itself (often |
| 25 | + // io.EOF). ReadLine returns err != nil if and only if the returned data is |
| 26 | + // not a complete line. |
| 27 | + // |
| 28 | + // If the implementation defines other methods for reading the same input, |
| 29 | + // line numbers may be incorrect if calls to ReadLine are mixed with calls |
| 30 | + // to other read methods. |
| 31 | + ReadLine() (string, int, error) |
| 32 | +} |
| 33 | + |
| 34 | +// NewLineReader returns a LineReader for a reader starting at a specific line |
| 35 | +// using the newline character, \n, as a line separator. If r is a |
| 36 | +// StringReader, it is used directly. Otherwise, it is wrapped in a way that |
| 37 | +// may read extra data from the underlying input. |
| 38 | +func NewLineReader(r io.Reader, lineno int) LineReader { |
| 39 | + sr, ok := r.(StringReader) |
| 40 | + if !ok { |
| 41 | + sr = bufio.NewReader(r) |
| 42 | + } |
| 43 | + return &lineReader{r: sr, n: lineno} |
| 44 | +} |
| 45 | + |
| 46 | +type lineReader struct { |
| 47 | + r StringReader |
| 48 | + n int |
| 49 | +} |
| 50 | + |
| 51 | +func (lr *lineReader) ReadLine() (line string, lineno int, err error) { |
| 52 | + lineno = lr.n |
| 53 | + line, err = lr.r.ReadString('\n') |
| 54 | + if err == nil { |
| 55 | + lr.n++ |
| 56 | + } |
| 57 | + return |
| 58 | +} |
0 commit comments